Reputation: 13
sorry to ask a basic question, but it is hard to find on google. anyway, I have a program that does math from numbers found in various .txt files. one thing I would like to add is a -show argument to show the math step by step (finding bugs in math, finding numbers from certian steps, etc.). I have it set up in the code like so:
import sys
sys.argv[0]
filename = sys.argv[1]
prop = sys.argv[2]
show = sys.argv[3]
if show == "-show":
show = 1
(show = 1 does something later on). my problem is when i don't put anything for sys.argv[3] like if i put:
python program.py examplefile.txt exampleline
then the program doesn't run, I know it is becauce it is expecting an argument and thats why its messing up, but is there a way to tell it that sys.argv[3] is not always used and can be blank?
Upvotes: 1
Views: 206
Reputation: 91007
On a side note, it might be good to checkout argparse
module in python, from the documentation -
The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.
It also has support for optional arguments. Maybe you can take a look at this to get started on that.
Upvotes: 1
Reputation:
You can check the length of sys.argv
, but why bother? Use try/catch:
try: flag = sys.argv[1]
except: flag = False
That way variable flag
always has a value, and you can write code the knows that it always has a value. The code has fewer lines than a if/else testing. It's a win all around.
Upvotes: 1
Reputation: 727
You should be getting an IndexError on that line when you run it without the third argument. If you're not getting an IndexError, something else is wrong and you should fix it. If you are, all is well - and you simply need to check for the length of sys.argv
, taking into account in your code what should happen when that value is 3 or 4:
if len(sys.argv) == 3:
# Stuff without sys.argv[3]
if len(sys.argv) == 4:
# Stuff with sys.argv[3]
Upvotes: 1