'Python argparse error: error: argument count: invalid int value
I am trying to run below code in jupyter notebook.
import argparse
parser = argparse.ArgumentParser(description='Example with non-optional arguments')
parser.add_argument('count', action="store", type=int)
parser.add_argument('units', action="store")
print(parser.parse_args())
but this gives this gives below error
usage: ipykernel_launcher.py [-h] count units
ipykernel_launcher.py: error: argument count: invalid int value: 'C:\\Users\\Kwan Lee\\AppData\\Roaming\\jupyter\\runtime\\kernel-76bf5bb5-ea74-42d5-8164-5c56b75bfafc.json'
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
c:\users\kwan lee\anaconda2\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py:2971: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
I am just trying to learn what argparse is but I don't get this error.
Solution 1:[1]
Normally a script like that is run as a stand alone file, e.g.
python foo.py 23 inches
The shell converts '23 inches' in a list of strings, which is available as sys.argv[1:]
inside the program.
parser.parse_args()
uses this sys.argv[1:]
as the default. But when run from within a Ipython session or Notebook, that list has the values that initialized the session. That file name given as an invalid integer value was part of that initialization, and isn't usable by your parser
.
To test this script you need to provide a relevant list of strings, e.g.
parser.parse_args(['23', 'lbs'])
Or import sys
and modify sys.argv
as described in one of the linked answers.
https://docs.python.org/3/library/argparse.html#beyond-sys-argv
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | hpaulj |