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]
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)
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With