Reputation: 2207
I have scripts:
moving1.py:
def move():
print("walk!")
moving2.py:
def move():
print("run!")
And man.py, that can accept by argument parameter moving1 or moving2 script to act.
man.py:
import sys
if len(sys.argv) <= 1:
exit("Too less arguments calling script")
__import__(sys.argv[1])
moving = sys.modules[sys.argv[1]]
def move():
moving.move()
Now I have testman.py script, that have to test all variants of man.py execution:
testman.py
import man #and somehow add here as argument "moving1"
man.move()
import man #and somehow add here as argument "moving2"
man.move()
There exist a lot of similar questions, but they don't do exactly what I want. How can I add arguments to imported scripts? Problem is not to check
if __name__ = "__main__":
there, problem is to import script exactly with parameters I want. Is it possible?
Upvotes: 10
Views: 29974
Reputation: 1336
If you are taking filename as command line argument and if you want to import it, then use imp load_source module.
import imp
module = imp.load_source("module.name", sys.argv[1])
#Then call the function
module.move()
Basically imp module helps to load the modules in run-time.
Hope this helps!
Upvotes: 6
Reputation: 7555
You should separate your argument handling code and your import code:
man.py
import sys
def move():
moving.move()
def setup(module):
global moving
moving = __import__(module)
if __name__ == "__main__":
if len(sys.argv) <= 1:
exit("Too less arguments calling script")
setup(sys.argv[1])
testman.py
import man
man.setup(<name>)
man.move()
However, this seems like a very odd way of acheiving what you are trying do do. Perhaps you could clarify your goals?
Upvotes: 9