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
sys.argvis a plain old list. You can use its elements the same way you'd use elements from any other list.