导入带有参数的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
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屋!