Import Python Script Into Another?
Solution 1:
It depends on how the code in the first file is structured.
If it's just a bunch of functions, like:
# first.py
def foo(): print("foo")
def bar(): print("bar")
Then you could import it and use the functions as follows:
# second.py
import first
first.foo() # prints "foo"
first.bar() # prints "bar"
or
# second.py
from first import foo, bar
foo() # prints "foo"
bar() # prints "bar"
or, to import all the names defined in first.py:
# second.py
from first import *
foo() # prints "foo"
bar() # prints "bar"
Note: This assumes the two files are in the same directory.
It gets a bit more complicated when you want to import names (functions, classes, etc) from modules in other directories or packages.
Solution 2:
It's worth mentioning that (at least in python 3), in order for this to work, you must have a file named __init__.py
in the same directory.