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
None is often used as a default argument value in Python because it allows us to call the function without providing a value for an argument that isn't required on each function invocation. None is especially useful for list and dict arguments.
In Python, to write empty functions, we use pass statement. pass is a special statement in Python that does nothing.
But some you may want to assign a null value to a variable it is called as Null Value Treatment in Python. Unlike other programming languages such as PHP or Java or C, Python does not have a null value. Instead, there is the 'None' keyword that you can use to define a null value.
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
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