1
votes

The problem is that I can not get through the first step of running the simplest command. When I write this code

import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

an then i get this error

usage: main.py [-h]
main.py: error: unrecognized arguments: -f
C:\Users\Saeid\AppData\Roaming\jupyter\runtime\kernel-301e1312-128e-4c4d-9ae8-
035b05a69a59.json

An exception has occurred, use %tb to see the full traceback.

SystemExit: 2

C:\Program Files\Anaconda3\lib\site-
packages\IPython\core\interactiveshell.py:2889: UserWarning: To exit: use
'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

3
Why are you even using argparse? What commandline arguments do you want to parse? Also how are you running this script? From shell? from within a running Ipython session? WIth the Ipython run? or something else. You haven't provided enough context.hpaulj

3 Answers

1
votes

The argparse module is used to parse command line arguments. Hence, it doesn't make much sense to do so in an IPython or Jupyter notebook. The error propably stems from the fact that the notebook was invoked with an -f option.

0
votes

As funky-future pointed out, you should not be using an IPython notebook with argparse. To test how it works, let's assume a file named test.py with the following content:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print(args.echo)

Now in your terminal (cmd or PowerShell) you go to the directory with the test.py file and type:

python test.py 123

The output should be:

123

Source

0
votes

To avoid that error message, you can do

import argparse
parser = argparse.ArgumentParser()
parser.parse_args([])