Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call a python file that requires a command line argument from within another python file?

For example, I have two python files, 'test1.py' and 'test2.py'. I want to import test2 into test1, so that when I run test1, it also runs test2.

However, in order to run properly, test2 requires an input argument. Normally when I run test2 from outside of test1, I just type the argument after the file call in the command line. How do I accomplish this when calling test2 from within test1?

like image 609
Solomon Avatar asked Oct 19 '15 16:10

Solomon


1 Answers

Assuming you can define your own test1 and test2 and that you are OK with using argparse (which is a good idea anyway):

The nice thing with using argparse is that you can let test2 define a whole bunch of default parameter values that test1 doesn't have to worry about. And, in a way, you have a documented interface for test2's calling.

Cribbed off https://docs.python.org/2/howto/argparse.html

test2.py

import argparse

def get_parser():
    "separate out parser definition in its own function"
    parser = argparse.ArgumentParser()
    parser.add_argument("square", help="display a square of a given number")
    return parser

def main(args):
    "define a main as the test1=>test2 entry point"
    print (int(args.square)**2)

if __name__ == '__main__':
    "standard test2 from command line call"
    parser = get_parser()
    args = parser.parse_args()
    main(args)

audrey:explore jluc$ python test2.py 3

9

test1.py

import test2
import sys

#ask test2 for its parser
parser = test2.get_parser()

try:
    #you can use sys.argv here if you want
    square = sys.argv[1]
except IndexError:
    #argparse expects strings, not int
    square = "5"

#parse the args for test2 based on what test1 wants to do
#by default parse_args uses sys.argv, but you can provide a list
#of strings yourself.
args = parser.parse_args([square])

#call test2 with the parsed args
test2.main(args)

audrey:explore jluc$ python test1.py 6

36

audrey:explore jluc$ python test1.py

25
like image 68
JL Peyret Avatar answered Sep 22 '22 22:09

JL Peyret