0

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 
1
  • sys.argv is a plain old list. You can use its elements the same way you'd use elements from any other list. Commented Aug 3, 2022 at 21:20

2 Answers 2

2

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]) 
Sign up to request clarification or add additional context in comments.

Comments

1

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]) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.