1

Say that I have a python script which can take in args

# testt.py
import argparse

def main(args):

    print(args.foo)
    print(args.bar)
    print(args.nee)

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description='Test argument parser')

    parser.add_argument('-foo', type=str)
    parser.add_argument('-bar', type=int)
    parser.add_argument('-nee', type=bool)
    args = parser.parse_args()

    main(args)

But instead of running it from the command line, I want to run it from another Python program

import testt

How could I pass in the arg parameters?

4
  • Your def main(): and main(args) conflict. Make up your mind. Is args supposed to a function argument, or a module global? Commented Jan 25, 2020 at 1:57
  • sorry, just fixed to def main(args) Commented Jan 25, 2020 at 2:01
  • Any object with those 3 attributes will work as a testt.main(foo) argument. Commented Jan 25, 2020 at 2:41
  • Some times it's cleaner to define main(foo, bar, nee). Then you can pass values without creating an object with attributes. Commented Jan 25, 2020 at 5:55

2 Answers 2

6

You can write a class for the arguments:

import testt

class TesttArgs:
    def __init__(self, foo, bar, nee):
        self.foo = foo
        self.bar = bar
        self.nee = nee

testt.main(TesttArgs('foo', 2, False))
Sign up to request clarification or add additional context in comments.

Comments

4

You could change the main() function in testt.py to do the parsing:

# testt.py
import sys
import argparse

def main(args):

    parser = argparse.ArgumentParser(description='Test argument parser')

    parser.add_argument('-foo', type=str)
    parser.add_argument('-bar', type=int)
    parser.add_argument('-nee', type=lambda x: bool(int(x)))
    args = parser.parse_args(args)

    print(args.foo)
    print(args.bar)
    print(args.nee)

if __name__ == "__main__":

    main(sys.argv[1:])

Then pass sys.argv[1:] to testt.main(), from whatever program imports testt:

# imp.py
import sys
import testt

if __name__ == "__main__":

    testt.main(sys.argv[1:])

One advantage is you no longer have to maintain a separate class when/if you change the command-line arguments you want to support.

This draws heavily from: How to use python argparse with args other than sys.argv?

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.