python中的main函数可以被其他文件调用么,在Python中,我可以调用导入模块的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.

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.

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:

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:])

Now you can import and call myModule.main(['arg1', 'arg2', 'arg3']) from other another module.

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)

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

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值