在Python中,我可以调用导入模块的main()? [英] In Python, can I call the main() of an imported module?

查看:1644
本文介绍了在Python中,我可以调用导入模块的main()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中我有一个模块 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脚本。现在,我愿把一切都变成小的,所以我想,也许我可以把我的简单的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.

那么,如何做我其实从main()函数调用的main() myModule.py的功能 MyFormerBashScript.py的?我甚至可以这样做吗?我如何通过任何参数呢?

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中作为参数传递(全code下同模块中的 Mymodule中

  • Parse them in main(), but pass in sys.argv as a parameter (all code below in the same module myModule):

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()接受已解析的参数(再次全部code在 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,巴兹='火腿')其他地方,并根据需要在Python中的参数传递。

and import and call myModule.main(foovalue, barvalue, baz='ham') elsewhere and passing in python arguments as needed.

这里的技巧是当你的模块被用作一个脚本来检测;当你运行一个python文件作为主脚本(蟒蛇filename.py )没有导入语句正在被使用,所以Python会自动调用该模块__ __主。但是,如果同一 filename.py code被视为一个模块(导入文件名),那么Python使用随着模块名称来代替。在这两种情况下,变量 __ __名设置,并针对测试告诉你如何你的code的运行。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆