Reputation: 77
I want to load oneRunParams.py into my current program but won't know where it is till I run it. I want to have it as an input argument, accessed through argv. I was using:
from oneRunParams import *
I now want to replace this with something that will do the same only with the path to oneRunParams specified.
Upvotes: 1
Views: 339
Reputation: 51175
You can use __import__
:
Here is test.py
:
# test.py
import sys
filename = sys.argv[1]
f = __import__(filename[:-3]) # This removes the `.py` extension
f.test()
Here is test2.py
:
# test2.py
def test():
print('hello world')
Running the following the command line:
python test.py test2.py
Gives the following output:
hello world
If you really want to load everything in local scope, you have to do the following:
filename = sys.argv[1]
f = __import__(filename[:-3], globals(), locals(), ['*'])
for k in dir(f):
locals()[k] = getattr(f, k)
test()
Upvotes: 2