'python -- calling function in one script from another script when there are multiple functions
I currently have 2 scripts test.py and connections.py. test.py is currently being used to just test code to be able to incorporate into other scripts. connections.py contains a set of functions to create a MySQL connection, close connection, and execute SQL statement.
The connections.py is to be used by multiple scripts that need to connect to the database. I know how to call the appropriate function when within the same script and I know how to call a function in another script when there is only one function in the script.
What I can't figure out is how to call the right function when there are multiple functions. Through google/stackoverflow all the examples I have found are when there is only one function or the call is being made in the same script.
I have tried using a class with functions in it and just a file with functions. Code below is without class. Any help is greatly appreciated. I am also using python 3.5 on windows 10 and it will eventually be moved to a UNIX machine if that makes any difference.
test.py
import connections as c
sql = "select * from tbl"
sqlRec = c.select_stmt(sql) # this is the command I need help with
print(sqlRec)
connections.py
import mysql.connector as MySQL
def connection():
#set up connection
con = MySQL.connect(user='xxx',password='xxx',host='xxx',db='xxx')
cursor = con.cursor()
return con, cursor
def close_connection(cursor,conn):
cursor.close()
con.close()
def select_stmt(sql):
con, cursor = connection()
cursor.execute(sql)
sqlRec = cursor.fetchall()
close_connection(cursor,con)
return sqlRec
def insert_update_stmt(sql):
con, cursor = connection()
cursor.execute(sql)
con.commit()
close_connection(cursor,con)
#if __name__ == '__main__':
# function_name_when_single_func(sql) //With a single function I had these uncommented and this worked to run function from another script
Solution 1:[1]
Specify the functions you want in your import statement.
For example:
## connections.py
def foo():
print("this is foo.")
def bar():
print("this is bar.")
## test.py
from connections import foo, bar
foo()
bar()
test.py output:
this is foo.
this is bar.
Process finished with exit code 0
Note
It's best to be explicit about the imports you're bringing in from another module.
From PEP 8:
Wildcard imports (from import *) should be avoided, as they make it unclear which names are present in the namespace.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | andrew_reece |
