4

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.

2
  • Possible duplicate of How to call module written with argparse in iPython notebook Commented May 15, 2018 at 22:58
  • From a notebook you need to call it as parser.parse_args(['5', 'inches']). That is, with simulated list of strings. The sys.argv used the run the notebook won't be the correct one for this script. Commented May 15, 2018 at 23:55

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

0

Replace

parser.add_argument('count', action="store", type=int)

with

parser.add_argument('--count', action="store", type=int)

Comments

0

In your case code should be like:

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")
parser.add_argument("-f", required=False)
print(parser.parse_args())

Tested with Google colab

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.