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()
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.
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.
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 .
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"])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With