mjoy
mjoy

Reputation: 700

How to run py script with function that takes arguments from command line?

I have a .py script that looks has a function that takes in arguments from the command line that I want to run. Normally, for a script named hi.py that isn't a function and looks like:

print('hello')

I will just type python hi.py to run the script.

However, I now have a py script names test.py that looks like:

def new_func(p1, p2):
    print('This is', p1)
    print('Next is', p2)

if __name__ == '__main__':
    new_func()

I need to take in from the command line the two function parameters. I know you can use sys if there is no function to call in the script like:

import sys
 
print('This is', sys.argv[1])
print('Next is', sys.argv[2])

and then do python script.py blue red to get

This is blue
Next is red

How can I run my script test.py in the command line to take in the arguments so that if I type:

python test.py orange red

Then I can run:

def new_func(p1, p2):
    print('This is', p1)
    print('Next is', p2)

if __name__ == '__main__':
    new_func()

where p1 = orange and p2 = red.

UPDATE: Thank you to blankettripod's answer! What if there is an argument that may or not be set. For example:

def new_func(p1, p2=None):
    if p2 == None:
        print('This is', p1)
    else: 
        print('This is', p1)
        print('Next is', p2)
    
    if __name__ == '__main__':
        new_func(sys.argv[1], sys.argv[2])

I tried just not giving a value for the second parameter but that doesn't work and I get the error:

IndexError: list index out of range

Upvotes: 0

Views: 569

Answers (2)

batreska
batreska

Reputation: 53

Try:

if __name__ == "__main__":
    try:
        new_func(sys.argv[1], sys.argv[2])
    except IndexError:
        new_func(sys.argv[1])

If you're not sure whether you will get first then you might want to use:

if __name__ == "__main__":
    number_of_args = len(sys.argv) -1 
    if number_of_args == 0:
        ...
    elif number_of_args == 1:
        new_func(sys.argv[1])
    elif number_of_args == 2:
        new_func(sys.argv[1], sys.argv[2])

Upvotes: 1

You can use sys.argv as parameters to your new_func function

e.g.

import sys

def new_func(p1, p2):
    print('This is', p1)
    print('Next is', p2)

if __name__ == '__main__':
    new_func(sys.argv[1], sys.argv[2])

Upvotes: 2

Related Questions