6

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()
3
  • Are you trying to get the arguments from foo.py into bar.py? Why not just move the parser into bar.py? Commented Sep 26, 2017 at 5:54
  • @Jalepeno112 As foo.py may be an separated module. Commented Sep 26, 2017 at 6:10
  • related: stackoverflow.com/questions/7336181/… Commented Aug 31, 2018 at 16:37

1 Answer 1

5

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

2 Comments

You don't need the if test. If passed_args is None parse_args uses sys.argv[1:].
@hpaulj Thanks, guys.

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.