Link to home
Start Free TrialLog in
Avatar of enthuguy
enthuguyFlag for Australia

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].split(':')





2nd Scenario:
============
Would like to introduce and pass 2nd argument state_list=sys.argv[2].split(':')

e.g
process.py nyc:denver:newjercy ny:ct:ny:co

Inside my process.py
city_list=sys.argv[1].split(':')
state_list=sys.argv[2].split(':')

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
Avatar of Duy Pham
Duy Pham
Flag of Viet Nam image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of enthuguy

ASKER

Thanks for your quick help
Avatar of pepr
pepr

I suggest the following
state_list = sys.argv[2].split(':') if len(sys.argv) >= 3 else []

Open in new window


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 = []

Open in new window

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).
Awesome.
Thanks pepr, this is a good one too