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?

SantoshGupta7
  • 5,607
  • 14
  • 58
  • 116

2 Answers2

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))
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
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?

bgstech
  • 624
  • 6
  • 12