Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if sys.argv[x] is defined

Tags:

python

What would be the best way to check if a variable was passed along for the script:

try:
    sys.argv[1]
except NameError:
    startingpoint = 'blah'
else:
    startingpoint = sys.argv[1]
like image 316
Cmag Avatar asked Sep 26 '22 15:09

Cmag


People also ask

How do you define SYS argv?

The first argument, sys. argv[0], is always the name of the program as it was invoked, and sys. argv[1] is the first argument you pass to the program. It's common that you slice the list to access the actual command line argument: import sys program_name = sys.argv[0] arguments = sys.argv[1:] count = len(arguments)

How do you check if an argument is present in Python?

Then you just have to call your parameters like this: if args['operation'] == "division": if not args['parameter']: ... if args['parameter'] == "euclidian": ... Show activity on this post. Show activity on this post.


1 Answers

Check the length of sys.argv:

if len(sys.argv) > 1:
    blah = sys.argv[1]
else:
    blah = 'blah'

Some people prefer the exception-based approach you've suggested (eg, try: blah = sys.argv[1]; except IndexError: blah = 'blah'), but I don't like it as much because it doesn't “scale” nearly as nicely (eg, when you want to accept two or three arguments) and it can potentially hide errors (eg, if you used blah = foo(sys.argv[1]), but foo(...) raised an IndexError, that IndexError would be ignored).

like image 153
David Wolever Avatar answered Oct 18 '22 01:10

David Wolever