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.

3
  • In file2.py: from file1 import * and then call your function Commented May 5, 2018 at 16:50
  • You seem to be looking for the import statement. E.g. from file1 import conn_db Commented May 5, 2018 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: stackoverflow.com/questions/20309456/… Commented May 5, 2018 at 16:54

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.