How to pass parameters to python function using argparse?

I have a foo.py using argparse to get command line parameters for the main() function.

""" foo.py """
import argparse

def main():
    parser = argparse.ArgumentParser(description='test')
    parser.add_argument('--all', '-a', action='store_true', help='all')
    args = parser.parse_args()

    if args.all:
        pass

if __name__ == '__main__':
    main()

And I have to test this main() function on another Python script bar.py. My question is how to pass parameters in bar.py. My current solution is changing the sys.argv. Looking for better solution.

""" bar.py """
import sys
import foo

if __name__ == '__main__':
    sys.argv.append('-a')
    foo.main()


您可以修改main函数来接收参数列表。

""" foo.py """
import argparse

def main(passed_args=None):
    parser = argparse.ArgumentParser(description='test')
    parser.add_argument('--all', '-a', action='store_true', help='all')
    if passed_args:
        args = parser.parse_args(passed_args)
    else:
        args = parser.parse_args()

    if args.all:
        pass

if __name__ == '__main__':
    main()

""" bar.py """
import sys
import foo

if __name__ == '__main__':
    foo.main(["-a"])
链接地址: http://www.djcxy.com/p/9304.html

上一篇: 服务器python和文件打开错误

下一篇: 如何使用argparse将参数传递给python函数?