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
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
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.
I think more appropriate way to do this would be to check if there's any parameter passed or not. If not then set category
to None
, otherwise set the value that is passed.
Ex:
if len(sys.argv) == 2: // or >= 2 in case of more parameter
category = sys.argv[1].strip()
else:
category = None
So if you just call script.py
, category will be set to None
.
If you call like script.py Value
, category will be set to Value
.
Piggybacking on @FraggaMuffin's answer, you may use a lambda function for convenience. Thus, instead of
parser.add_argument('category', type=none_or_str, nargs='?', default=None,
help='the category of the stuff')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.