[英]Import python script with arguments
I have scripts: 我有脚本:
moving1.py : moving1.py :
def move():
print("walk!")
moving2.py : moving2.py :
def move():
print("run!")
And man.py , that can accept by argument parameter moving1 or moving2 script to act. 而man.py ,可以通过参数move1或moving2脚本来接受。
man.py : 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脚本,必须测试man.py执行的所有变体:
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?
可能吗?
If you are taking filename as command line argument and if you want to import it, then use imp load_source module. 如果要将filename作为命令行参数,并且要导入它,则使用imp load_source模块。
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. 基本上,imp模块有助于在运行时加载模块。
Hope this helps! 希望这可以帮助!
You should separate your argument handling code and your import code: 您应该将参数处理代码和导入代码分开:
man.py 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 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?
也许你可以澄清你的目标?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.