4

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()?

0

1 Answer 1

8

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"])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.