Using procedures in python

Using procedures in python

by Dale Fugier (Last updated: Wednesday, December 12, 2018)

Overview

In Python a function is a named block of code that can perform a reusable action. This allows Python code to be broken down into functional, reusable blocks of code.

There are many modules available for Python. These modules contain a great number of pre-defined procedures that can be very useful. There are libraries that help with Date, Time, Math, etc.

Import Modules

You can use any Python file as a module by using the import statement. Once imported all the procedures in the import are available. The standard syntax for importing is:

To import more the one module, use commas to separate module names:

import rhinoscriptsyntax, time, math 

To access procedures in imported modeles, prefix the function with the imported model name, seperated by a period (.):

import time print (time.strftime("%H:%M:%S")) #strftime is a proccedure in the time module. 

The import statement can also be used to change the reference name of the incoming module. Use this function to make module names shorter to use and easier to read in the code. A very common example of this is how we normally will shorted the rhinoscriptsyntax module to rs for convenience:

import rhinoscriptsyntax as rs rs.AddPoint (1, 2, 3) # The Rhinoscriptsyntax module is accessed throught 'rs' abreviation. 

It is also possible to import only a portion of a module. In the following case, only certain namespaces are imported from the larger Syste.IO module:

from System.IO import Path, File, FileInfo, FileAttributes 

The imported modules above are referenced by using Path , File , FileInfo , FileAttributes as namespaces.

Common Modules

There are many modules available for Python. Some of the most useful to Rhino Python are:

  • Rhinoceros modules
    • rhinoscriptsyntax — The basic rhino library of procedures
    • rhino —
    • string — Common string operations
    • StringIO — Read and write strings as files
    • fpformat — Floating point conversions
    • datetime — Basic date and time types
    • time — Time access and conversions
    • math — Mathematical functions
    • fractions — Rational numbers
    • random — Generate pseudo-random numbers
    • System.IO — Common pathname manipulations
    • tempfile — Generate temporary files and directories
    • csv — CSV File Reading and Writing

    A complete list of predefined modules in Python, see the Python Standard Library modules

    User-Defined Procedures

    A Function is a series of Python statements begins by a def , followed by the function name and enclosed in parenthesis. A Function may or may not return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a Function procedure has no arguments, its def statement should include an empty set of parentheses () . Parameters can also be defined within the parenthesis. The parenthesis are followed by a colon (:) to end the first line.

    The end of the function is marked by the loss of whitespace in the next line of the code (ending the code block). It is common practice to use a return statement followed by the argument to return a value. You may also finish a function with a return statement and a simple colon (;).

    In the following example, the Celsius def calculates degrees Celsius from degrees Fahrenheit. When the def is called from the ConvertTemp def procedure, a variable containing the argument value is passed to the def. The result of the calculation is returned to the calling procedure and displayed in a message box.

    def Celsius(fDegrees): _Celsius = (fDegrees - 32) * 5 / 9 return _Celsius; # Use this code to call the Celsius function temp = raw_input("Please enter the temperature in degrees F.", 1) MsgBox "The temperature is " & Celsius(temp) & " degrees C." 

    Getting Data In and Out

    Each piece of data is passed into your procedures using an argument. Arguments serve as placeholders for the data you want to pass into your procedure. You can name your arguments any valid variable name. When you create a procedure parentheses must be included after the name of the procedure. Any arguments are placed inside these parentheses, separated by spaces. For example, in the following example, fDegrees is a placeholder for the value being passed into the Celsius function for conversion.

    Function Celsius(fDegrees) _Celsius = (fDegrees - 32) * 5 / 9 return _Celsius; 

    To call a procedure from another procedure, type the name of the procedure along with values for any required arguments, each separated by a space.

    The function will returns a single value based on its final return statement. A return statement with a variable name, followed by a semicolon (;) returns the reference to that variable. A return statement with simply a semicolon (;) returns nothing. The return statement is not required to end a procedure.

    Assigning a Function to a Variable

    Python allows a variable to contain a function.

    Источник

    Python Execute MySQL Stored Procedure

    In this lesson, you will learn how to execute MySQL stored procedures in Python.

    Further Reading:

    Table of contents

    Prerequisites

    Before moving further, make sure you have the following in place.

    • Username and password that you need to connect to MySQL
    • MySQL stored procedure name which you want to call.

    For this lesson, I have created a stored procedure get_laptop under the “Electronics” database. This procedure fetches laptop details from the Laptop table based on the laptop id passed as an IN parameter

    If a table is not present in your MySQL server, you can refer to our article to create a MySQL table from Python.

    You can also download a SQL query file, which contains SQL queries for table creation and data so that you can use this table for your SQL operations.

    If you already know the stored procedure you want to execute, you can skip the following query. Else, open the MySQL console and run the below query to create a MySQL Stored Procedure.

    DELIMITER $ USE Electronics$ CREATE * from Laptop where $ DELIMITER ;

    Now you know the stored procedure to execute, so let’s move to our example.

    Note: We are using the MySQL Connector Python module to execute a MySQL Stored Procedure.

    Steps to execute MySQL Stored Procedure in Python

    To call MySQL stored procedure from Python, you need to follow these steps: –

    How to execute MySQL stored procedure in Python

    1. Connect to MySQL from Python Refer to Python MySQL database connection to connect to MySQL database from Python using MySQL Connector module
    2. Get Cursor Object from Connection Next, use a connection.cursor() method to create a cursor object. This method creates a new MySQLCursor object.
    3. Execute the stored procedure Execute the stored procedure using the cursor.callproc() . here, you must know the stored procedure name and its IN and OUT parameters. For example, cursor.callproc(‘get_laptop’,[1,])
    4. Fetch results Once the stored procedure executes successfully, we can extract the result using a cursor.stored_results()
    5. Close the cursor object and database connection object use cursor.clsoe() and connection.clsoe() method to close open connections after your work completes.

    Execute MySQL stored procedure in python

    Now, let see the example. In this example, we are going to execute the get_laptop stored procedure using Python.

    import mysql.connector from mysql.connector import Error try: connection = mysql.connector.connect(host='localhost', database='Electronics', user='pynative', password='pynative@#29') cursor = connection.cursor() cursor.callproc('get_laptop', [1, ]) # print results print("Printing laptop details") for result in cursor.stored_results(): print(result.fetchall()) except mysql.connector.Error as error: print("Failed to execute stored procedure: <>".format(error)) finally: if (connection.is_connected()): cursor.close() connection.close() print("MySQL connection is closed")

    You should get the following output.

    Printing laptop details [(1, 'Lenovo ThinkPad P71', 6459.0, datetime.date(2019, 8, 14))] MySQL connection is closed

    Note: Also, catch any SQL exceptions that may occur during this process.
    Use the MySQL Connector module’s Error class, which shows us an error when we failed to execute a stored procedure. Example ER_ACCESS_DENIED_ERROR when username or password is wrong.

    Cursor callproc() Method

    result_args = cursor.callproc(proc_name, args=())

    The callproc() method calls the stored procedure mentioned in the proc_name argument. The args sequence of parameters must contain one entry for each argument that the procedure expects. For example, the procedure can have one or many IN and OUT parameters.

    The callproc() returns a modified copy of the input sequence. This method doesn’t change the input parameters. However, It can replace the output and input/output parameters with new values as per the execution result.

    The stored procedure returns the output in result sets, and It is automatically fetched and stored as MySQLCursorBuffered instances.

    For example, a stored procedure “addition” takes two parameters, adds the values, and returns the sum.

    CREATE PROCEDURE add_num(IN num1 INT, IN num2 INT, OUT sum INT) BEGIN SET sum := num1 + num2; END;

    The following example shows how to execute this Add procedure in Python.

    args = (5, 6, 0) # 0 is to hold value of the OUT parameter sum cursor.callproc('add_num', args)

    Next Steps:

    To practice what you learned in this article, Please solve a Python Database Exercise project to Practice and master the Python Database operations.

    Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

    About Vishal

    I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

    Python Exercises and Quizzes

    Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

    • 15+ Topic-specific Exercises and Quizzes
    • Each Exercise contains 10 questions
    • Each Quiz contains 12-15 MCQ

    Источник

    Читайте также:  Json content type text javascript
Оцените статью