How to check if an argument is installed from the command line?

I can name my script as follows:

python D:\myscript.py 60 

And in the script, I can do:

 arg = sys.argv[1] foo(arg) 

But how can I check if an argument was entered in a command line call? I need to do something like this:

 if isset(sys.argv[1]): foo(sys.argv[1]) else: print "You must set argument!!!" 
+14
python
Nov 15 '10 at 20:24
source share
7 answers

Do not use sys.argv to process the command line interface; There is a module for this: argparse .

You can mark the argument as required by passing required=True to add_argument .

 import argparse parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument("foo", ..., required=True) parser.parse_args() 
+31
Nov 15 '10 at 20:28
source share

len(sys.argv) > 1

+31
Nov 15 '10 at 20:27
source share
 if len(sys.argv) < 2: print "You must set argument!!!" 
+19
Nov 15 '10 at 20:28
source share

If you are using Python 2.7 / 3.2, use the argparse module. Otherwise, use the optparse module. The module takes care of parsing the command line, and you can check whether the number of positional arguments matches the expected one.

+5
Nov 15 '10 at 20:29
source share

I use the optparse module for this, but I think because I use 2.5, you can use argparse, as Alex suggested, if you use 2.7 or more

0
Nov 15 '10 at 21:15
source share
 for arg in sys.argv: print (arg) #print cli arguments 

You can use it to store an argument in a list and use it. This is a safer way than using them like this sys.argv[n]

No problem if no arguments are given

0
Aug 21 '14 at 13:02
source share

if(sys.argv[1]): should work fine, if there are no arguments sys.argv [1] will (should be) null

-7
Nov 15 '10 at 20:27
source share



All Articles