enthuguy
asked on
how to handle null argument in python
1st Scenario
============
Currently have a python script which accepts 1 argument and does something.
process.py nyc:denver:newjercy
Inside my process.py
city_list=sys.argv[1].spli t(':')
2nd Scenario:
============
Would like to introduce and pass 2nd argument state_list=sys.argv[2].spl it(':')
e.g
process.py nyc:denver:newjercy ny:ct:ny:co
Inside my process.py
city_list=sys.argv[1].spli t(':')
state_list=sys.argv[2].spl it(':')
Upto this stage it works fine.
But now
========
if I dont pass 2nd argument to my process.py it fails with below Error. Which I understand bcuz I'm not passing the argument.
IndexError: index out of range: 2
Request is:
How to handle 2nd argument inside python script. If I pass 'none', is it easy to handle? pls help with sample script.
============
Currently have a python script which accepts 1 argument and does something.
process.py nyc:denver:newjercy
Inside my process.py
city_list=sys.argv[1].spli
2nd Scenario:
============
Would like to introduce and pass 2nd argument state_list=sys.argv[2].spl
e.g
process.py nyc:denver:newjercy ny:ct:ny:co
Inside my process.py
city_list=sys.argv[1].spli
state_list=sys.argv[2].spl
Upto this stage it works fine.
But now
========
if I dont pass 2nd argument to my process.py it fails with below Error. Which I understand bcuz I'm not passing the argument.
IndexError: index out of range: 2
Request is:
How to handle 2nd argument inside python script. If I pass 'none', is it easy to handle? pls help with sample script.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I suggest the following
This is called a conditional expression, and works the same way as
It does not matter (what solution you choose) too much for getting the sys.argv if the program is short. If there is more complex processing of command-line arguments, then have a look at the argparse standard module (https://docs.python.org/3.5/library/argparse.html).
state_list = sys.argv[2].split(':') if len(sys.argv) >= 3 else []
This is called a conditional expression, and works the same way as
if len(sys.argv) >= 3:
state_list = sys.argv[2].split(':')
else:
state_list = []
But the conditional expression is better here. It is more dense (fewer lines), the state_list is not repeated (less error-prone as you cannot create two variables by typo error). Actually only the first part of the expression is the important one (this is what should be done); so, you can skip the rest if you are re-reading the source to get the idea.It does not matter (what solution you choose) too much for getting the sys.argv if the program is short. If there is more complex processing of command-line arguments, then have a look at the argparse standard module (https://docs.python.org/3.5/library/argparse.html).
ASKER
Awesome.
Thanks pepr, this is a good one too
Thanks pepr, this is a good one too
ASKER