Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 588
northtree Avatar asked Sep 26 '17 05:09

northtree


People also ask

How do you pass arguments to Argparse?

First, we need the argparse package, so we go ahead and import it on Line 2. On Line 5 we instantiate the ArgumentParser object as ap . Then on Lines 6 and 7 we add our only argument, --name . We must specify both shorthand ( -n ) and longhand versions ( --name ) where either flag could be used in the command line.

How do you pass arguments to a Python script?

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys. argv ) will store all the information in the command line entry and can be accessed inside the Python script. Python's getopt module can also be used to parse named arguments.

What does Argparse ArgumentParser ()?

Python argparse The argparse module also automatically generates help and usage messages, and issues errors when users give the program invalid arguments. The argparse is a standard module; we do not need to install it. A parser is created with ArgumentParser and a new parameter is added with add_argument .


1 Answers

You can modify main function to receive a list of args.

""" foo.py """
import argparse

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

    if args.all:
        pass

if __name__ == '__main__':
    main()

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

if __name__ == '__main__':
    foo.main(["-a"])
like image 77
Sraw Avatar answered Oct 02 '22 09:10

Sraw