Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass arguments to imported script in Python

I have a script (script1.py) of the following form:

#!/bin/python

import sys

def main():
    print("number of command line options: {numberOfOptions}".format(numberOfOptions = len(sys.argv)))
    print("list object of all command line options: {listOfOptions}".format(listOfOptions = sys.argv))
    for i in range(0, len(sys.argv)):
        print("option {i}: {option}".format(i = i, option = sys.argv[i]))

if __name__ == '__main__':
    main()

I want to import this script in another script (script2.py) and pass to it some arguments. The script script2.py could look something like this:

import script1

listOfOptions = ['option1', 'option2']
#script1.main(listOfOptions) insert magic here

How could I pass the arguments defined in script2.py to the main function of script1.py as though they were command line options?

So, for example, would it be Pythonic to do something such as the following?:

import script1
import sys

sys.argv = ['option1', 'option2']
script1.main()
like image 403
d3pd Avatar asked Jun 11 '14 18:06

d3pd


People also ask

How do you give a Python script a command line input?

If so, you'll need to use the input() command. The input() command allows you to require a user to enter a string or number while a program is running. The input() method replaced the old raw_input() method that existed in Python v2. Open a terminal and run the python command to access Python.

How do you pass a file path as a command line argument in Python?

To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest: Notice two things here: You should use forward slashes with pathlib functions. The Path() object will convert forward slashes into the correct kind of slash for the current operating system.


1 Answers

Separate command line parsing and called function

For reusability of your code, it is practical to keep the acting function separated from command line parsing

scrmodule.py

def fun(a, b):
    # possibly do something here
    return a + b

def main():
    #process command line argumens
    a = 1 #will be read from command line
    b = 2 #will be read from command line
    # call fun()
    res = fun(a, b)
    print "a", a
    print "b", b
    print "result is", res

if __name__ == "__main__":
    main()

Reusing it from another place

from scrmodule import fun

print "1 + 2 = ", fun(1, 2)
like image 118
Jan Vlcinsky Avatar answered Sep 20 '22 18:09

Jan Vlcinsky