Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if the parameter exist in python

Tags:

python

linux

I would like to create a simple python script that will take a parameter from the console, and it will display this parameter. If there will be no parameter then I would like to display error message, but custom message not something like IndexError: list index out of range

Something like this:

if isset(sys.argv[1]):
    print sys.argv[1];
else:
    print "No parameter has been included"
like image 558
M4tt Avatar asked Jun 07 '26 05:06

M4tt


1 Answers

if len(sys.argv) >= 2:
    print(sys.argv[1])
else:
    print("No parameter has been included")

For more complex command line interfaces there is the argparse module in Python's standard library - but for simple projects taking just a couple parameters directly checking sys.argv is alright.

update as of 2019, the recomendation is to use the external library "click", as it provides very "Pythonic" ways of including complex documents in a way they are easily documented.

like image 188
jsbueno Avatar answered Jun 10 '26 07:06

jsbueno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!