在 Python 中,我可以调用导入模块的 main() 吗? [英] In Python, can I call the main() of an imported module?
问题描述
在 Python 中,我有一个 module myModule.py,我在其中定义了一些函数和一个 main(),它需要一些命令行参数.
In Python I have a module myModule.py where I define a few functions and a main(), which takes a few command line arguments.
我通常从 bash 脚本中调用 main().现在,我想把所有东西都放在一个小的包中,所以我想也许我可以把我的简单的bash脚本变成一个Python脚本并把它放在包里.
I usually call this main() from a bash script. Now, I would like to put everything into a small package, so I thought that maybe I could turn my simple bash script into a Python script and put it in the package.
那么,我实际上如何从 MyFormerBashScript.py 的 main() 函数调用 myModule.py 的 main() 函数?我什至可以这样做吗?我如何将任何参数传递给它?
So, how do I actually call the main() function of myModule.py from the main() function of MyFormerBashScript.py? Can I even do that? How do I pass any arguments to it?
推荐答案
这只是一个函数.导入并调用它:
It's just a function. Import it and call it:
import myModule
myModule.main()
如果你需要解析参数,你有两个选择:
If you need to parse arguments, you have two options:
在
main()
中解析它们,但将sys.argv
作为参数传入(以下所有代码在同一模块myModule代码>):
Parse them in
main()
, but pass insys.argv
as a parameter (all code below in the same modulemyModule
):
def main(args):
# parse arguments using optparse or argparse or what have you
if __name__ == '__main__':
import sys
main(sys.argv[1:])
现在您可以从其他模块导入和调用 myModule.main(['arg1', 'arg2', 'arg3'])
.
Now you can import and call myModule.main(['arg1', 'arg2', 'arg3'])
from other another module.
让 main()
接受已经解析的参数(同样是 myModule
模块中的所有代码):
Have main()
accept parameters that are already parsed (again all code in the myModule
module):
def main(foo, bar, baz='spam'):
# run with already parsed arguments
if __name__ == '__main__':
import sys
# parse sys.argv[1:] using optparse or argparse or what have you
main(foovalue, barvalue, **dictofoptions)
并在其他地方导入和调用 myModule.main(foovalue, barvalue, baz='ham')
并根据需要传入 Python 参数.
and import and call myModule.main(foovalue, barvalue, baz='ham')
elsewhere and passing in python arguments as needed.
这里的技巧是检测您的模块何时被用作脚本;当您将 python 文件作为主脚本 (python filename.py
) 运行时,没有使用 import
语句,因此 python 调用该模块 "__main__"代码>.但是如果相同的
filename.py
代码被视为一个模块(import filename
),那么 python 将使用它作为模块名称.在这两种情况下,变量 __name__
都已设置,针对该变量的测试会告诉您代码是如何运行的.
The trick here is to detect when your module is being used as a script; when you run a python file as the main script (python filename.py
) no import
statement is being used, so python calls that module "__main__"
. But if that same filename.py
code is treated as a module (import filename
), then python uses that as the module name instead. In both cases the variable __name__
is set, and testing against that tells you how your code was run.
这篇关于在 Python 中,我可以调用导入模块的 main() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!