使用参数导入 python 脚本 [英] Import python script with arguments
问题描述
我有脚本:
moving1.py:
def move():
print("walk!")
moving2.py:
def move():
print("run!")
和man.py,可以接受通过参数参数moving1或moving2脚本来执行.
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()
现在我有了 testman.py 脚本,它必须测试 man.py 执行的所有变体:
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?
推荐答案
你应该把你的参数处理代码和你的导入代码分开:
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?
这篇关于使用参数导入 python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!