0

I have a function that connects to a database thats predefined. The code looks like: file1.py

def conn_db():
    try:
        cursor = pymysql.cursors.DictCursor
        conn = pymysql.connect(host=settings.host,
                                user=settings.user,
                                password=settings.password,
                                db=settings.database,
                                port=settings.port,
                                cursorclass=cursor)
        dbcursor = conn.cursor()
    except pymysql.err.OperationalError as e:
        print("Unable to make a connection to the mysql database. \n Error was:{}".format(e))

    return conn, dbcursor

How can I use this function conn_db from file1.py in file2.py. And then call file2.py from executing python's intrepreter via python ?

Having a hard time even identifying something so basic, after several attempts.

Thank you.

John
  • 155
  • 4
  • 16
  • In file2.py: `from file1 import *` and then call your function – mnistic May 05 '18 at 16:50
  • You seem to be looking for the `import` statement. E.g. `from file1 import conn_db` – khelwood May 05 '18 at 16:50
  • John, please google your questions before asking them here. A simple "call function from another file python" in google search would've yielded you the answer. This question might get downvoted and closed soon. More info: https://stackoverflow.com/questions/20309456/call-a-function-from-another-file-in-python – Rahul Bharadwaj May 05 '18 at 16:54

1 Answers1

1

You can use import file1 and then use file1.conn_db() to use the function.

khelwood
  • 55,782
  • 14
  • 81
  • 108
tristan
  • 98
  • 8