Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - simulate sys.argv when calling script as function without modifying it

Tags:

python

I have an existing script that uses this structure

def main():
    import argparse
    cmd_parser = argparse.ArgumentParser(description='A tool to work with MicroPython .mpy files.')
    cmd_parser.add_argument('-d', '--dump', action='store_true',
        help='dump contents of files')
    cmd_parser.add_argument('-f', '--freeze', action='store_true',
        help='freeze files')
    cmd_parser.add_argument('-q', '--qstr-header',
        help='qstr header file to freeze against')
    cmd_parser.add_argument('-mlongint-impl', choices=['none', 'longlong', 'mpz'], default='mpz',
        help='long-int implementation used by target (default mpz)')
    cmd_parser.add_argument('-mmpz-dig-size', metavar='N', type=int, default=16,
        help='mpz digit size used by target (default 16)')
    cmd_parser.add_argument('files', nargs='+',
        help='input .mpy files')
    args = cmd_parser.parse_args()

if __name__ == '__main__':
    main()

Normally, I've been calling it via command line but I plan on importing this script and calling it thus: theScript.main().

The issue is that (I don't think) sys.argv will be what this function expects; sys.argv will be set to the calling script's values.

What is the most Pythonic way to simulate me calling theScript from another script but as if it is being called from the command line?

Should I just manually modify sys.argv before calling theScript.main()?

like image 973
Bob Avatar asked Oct 25 '25 09:10

Bob


1 Answers

don't change sys.argv. parse_args takes sys.argv[1:] by default, but you can pass other arguments if you want allowing to call main from another python module.

def main(args):
    import argparse
    ...
    args = cmd_parser.parse_args(args)

main(["-d","-f"])
like image 122
Jean-François Fabre Avatar answered Oct 27 '25 22:10

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!