How to pass None keyword as command line argument
I am trying to pass None
keyword as a command line parameter to a script as follows, if I explicity mention Category=None
it works but the moment I switch to sys.argv[1]
it fails, any pointers on how to fix this?
category = None --> works
#category=sys.argv[1] --> doesn't work
so I tried as below which still didn't work
if sys.argv[1].strip()==None:
category = None
else:
category=sys.argv[1].strip()
Command line passage:
script.py None
Solution 1:
As Stephen mentioned, None
is not a string, so when comparing a str
type to a NoneType
type, the result will always be False
.
If I just put "
around None
on the right-hand-side of the comparison, we get:
import sys
if sys.argv[1].strip() == "None":
category = None
else:
category = sys.argv[1].strip()
print(category)
print(type(category))
Resulting in:
~/temp $ python script.py 123
123
<type 'str'>
~/temp $ python script.py None
None
<type 'NoneType'>
argparse
instead?
However, I recommend using argparse instead, if you're in a position to do so. I use it all the time.
The above code could be replaced with:
import argparse
parser = argparse.ArgumentParser(description='Do some cool stuff.')
def none_or_str(value):
if value == 'None':
return None
return value
parser.add_argument('category', type=none_or_str, nargs='?', default=None,
help='the category of the stuff')
args = parser.parse_args()
print(args.category)
print(type(args.category))
Which will also tolerate no parameters
~/temp $ python script.py
None
<type 'NoneType'>
~/temp $ python script.py 123
123
<type 'str'>
~/temp $ python script.py None
None
<type 'NoneType'>
And it auto-formats some help text for you!
~/temp $ python script.py --help
usage: script.py [-h] [category]
Do some cool stuff.
positional arguments:
category the category of the stuff
optional arguments:
-h, --help show this help message and exit
Solution 2:
just an FYI. You can use ast module to convert sting 'None' to None type
Ex:
import ast
if not ast.literal_eval(sys.argv[1]):
print "Input Arg is None"
or
if sys.argv[1].strip() == 'None':
print "Input Arg is None"
Faster and better solution.