An exception has occurred, use %tb to see the full traceback. SystemExit: 2 - python

can anyone tell me how to make this code works in jupyter or any notebook
Code
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to input image")
ap.add_argument("-p", "--prototxt", required=True, help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True, help="path to Caffe pre-trained model")
ap.add_argument("-c", "--confidence", type=float, default=0.2, help="minimum probability to filter weak detections")
args = vars(ap.parse_args())
Error
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
I've tried some solutions but none work

Related

Error during constructing the argument parse and parse the arguments

Why my argument parse has an error although I have already defined the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="path to the input image")
ap.add_argument("-w", "--width", type=float, required=True,
help="width of the left-most object in the image (in inches)")
args = vars(ap.parse_args())
and the error says that
usage: main.py [-h] -i IMAGE -w WIDTH
main.py: error: the following arguments are required: -i/--image, -w/--width

Command line arguments are not working in python

--A_Z_Handwritten Data.csv: The path to the Kaggle A-Z dataset (Lines 3 and 4)
--HandWritingRecognition: The path to output the trained handwriting recognition model (Lines 5 and 6)
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-a", "--A_Z_Handwritten Data.csv", required=True,
help="path to A-Z dataset")
ap.add_argument("-m", "--HandWritingRecognition", type=str, required=True,
help="path to output trained handwriting recognition mode")
# ap.add_argument("-p", "--plot", type=str, default="plot.png",
# help="/home/gaurav/Desktop/HandWritingRecognition/")
args = vars(ap.parse_args())
This is the error...!
usage: ipykernel_launcher.py [-h] -a A_Z_HANDWRITTEN DATA.CSV -m
HANDWRITINGRECOGNITION
ipykernel_launcher.py: error: the following arguments are required: -a/--A_Z_Handwritten Data.csv, -m/--HandWritingRecognition
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2

How to run my Python code using Spyder, without the error "the following arguments are required: -p/--shape-predictor"?

How can I run this?
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--shape-predictor", required=True,
help="path to facial landmark predictor")
ap.add_argument("-a", "--alarm", type=str, default="",
help="path alarm .WAV file")
ap.add_argument("-w", "--webcam", type=int, default=0,
help="index of webcam on system")
args = vars(ap.parse_args())
While I run this on Spyder it gives
usage: [-h] -p SHAPE_PREDICTOR [-a ALARM] [-w WEBCAM]
: error: the following arguments are required: -p/--shape-predictor
An exception has occurred, use %tb to see the full traceback.
How can I solve this issue?
From #hiroprotagonist's comment posted above:
In spyder ctrl+F6 should allow you to pass command-line args when you execute your script. see here https://stackoverflow.com/a/26766414/4954037.

Argparse - SystemExit:2

import argparse
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="path to input image")
ap.add_argument("-p", "--prototxt", required=True,
help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,
help="path to Caffe pre-trained model")
ap.add_argument("-c", "--confidence", type=float, default=0.5,
help="minimum probability to filter weak detections")
args = vars(ap.parse_args())
I'm running a face recognition example through OpenCV.
I use 'argparse' at this point, and get this error.
args = vars(ap.parse_args())
from this code.
usage: ipykernel_launcher.py [-h] -i IMAGE -p PROTOTXT -m MODEL
[-c CONFIDENCE]
ipykernel_launcher.py: error: the following arguments are required: -i/--
image, -p/--prototxt, -m/--model
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
C:\Users\user\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py:2918: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
How can I solve it?
This is my computer environment and use the Jupyter-notebook
Python: 3.6.4 64bit [MSC v.1900 64 bit (AMD64)]
IPython: 6.2.1
OS: Windows 10 10.0.15063 SP0
argparse: 1.1
This is hard to answer without you sharing how you try to run the file. The error is telling you it did not find the required arguments passed in when you ran the file.
Since you specified required = True for the -i, -p, and -m arguments you must always pass them in or make them optional if they are not needed to run your program.
In an ipython session:
In [36]: import argparse
In [37]: # construct the argument parse and parse the arguments
...: ap = argparse.ArgumentParser()
...: ap.add_argument("-i", "--image", required=True,
...: help="path to input image")
...: ap.add_argument("-p", "--prototxt", required=True,
...: help="path to Caffe 'deploy' prototxt file")
...: ap.add_argument("-m", "--model", required=True,
...: help="path to Caffe pre-trained model")
...: ap.add_argument("-c", "--confidence", type=float, default=0.5,
...: help="minimum probability to filter weak detections")
...: args = vars(ap.parse_args())
...:
usage: ipython3 [-h] -i IMAGE -p PROTOTXT -m MODEL [-c CONFIDENCE]
ipython3: error: the following arguments are required: -i/--image, -p/--prototxt, -m/--model
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py:2918: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
I can run this parser by modifying sys.argv:
In [39]: import sys
In [40]: sys.argv[1:]
Out[40]:
['--pylab',
'--nosep',
'--term-title',
'--InteractiveShellApp.pylab_import_all=False']
In [41]: sys.argv[1:] = '-i image -p proto -m amodel'.split()
In [42]: args = ap.parse_args()
In [43]: args
Out[43]: Namespace(confidence=0.5, image='image', model='amodel', prototxt='proto')
or with
In [45]: ap.parse_args('-i image -p proto -m amodel'.split())
Out[45]: Namespace(confidence=0.5, image='image', model='amodel', prototxt='proto')
I often use this method to test a parser.
If this parser was in a script, and I ran it from command line without the arguments, it would print the usage and then exit. That exit is what ipython is catching and displaying as SystemExit: 2.
I think you should set required=True to False

Argparse in iPython notebook: unrecognized arguments: -f

I am trying to pass a .py file to ipython notebook environment.
I have never had to deal directly with argparse before. How do I rewrite the main() function?
I tried to delete the line of def main(): and keep the rest of the code.
But args = parser.parse_args()" returned an error:
ipykernel_launcher.py: error: unrecognized arguments: -f.
And when I run . %tb:
showing this
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', type=str, default='data/tinyshakespeare',
help='data directory containing input.txt')
parser.add_argument('--input_encoding', type=str, default=None,
help='character encoding of input.txt, from https://docs.python.org/3/library/codecs.html#standard-encodings')
parser.add_argument('--log_dir', type=str, default='logs',
help='directory containing tensorboard logs')
parser.add_argument('--save_dir', type=str, default='save',
help='directory to store checkpointed models')
parser.add_argument('--rnn_size', type=int, default=256,
help='size of RNN hidden state')
parser.add_argument('--num_layers', type=int, default=2,
help='number of layers in the RNN')
parser.add_argument('--model', type=str, default='lstm',
help='rnn, gru, or lstm')
parser.add_argument('--batch_size', type=int, default=50,
help='minibatch size')
parser.add_argument('--seq_length', type=int, default=25,
help='RNN sequence length')
parser.add_argument('--num_epochs', type=int, default=50,
help='number of epochs')
parser.add_argument('--save_every', type=int, default=1000,
help='save frequency')
parser.add_argument('--grad_clip', type=float, default=5.,
help='clip gradients at this value')
parser.add_argument('--learning_rate', type=float, default=0.002,
help='learning rate')
parser.add_argument('--decay_rate', type=float, default=0.97,
help='decay rate for rmsprop')
parser.add_argument('--gpu_mem', type=float, default=0.666,
help='%% of gpu memory to be allocated to this process. Default is 66.6%%')
parser.add_argument('--init_from', type=str, default=None,
help="""continue training from saved model at this path. Path must contain files saved by previous training process:
'config.pkl' : configuration;
'words_vocab.pkl' : vocabulary definitions;
'checkpoint' : paths to model file(s) (created by tf).
Note: this file contains absolute paths, be careful when moving files around;
'model.ckpt-*' : file(s) with model definition (created by tf)
""")
args = parser.parse_args()
train(args)
You can try args = parser.parse_args(args=[]).
It's better to use #nbro 's answer for Jupyter execution.
args = parser.parse_args(args=[])
If you want to manage parameters as class format, you can try this.
class Args:
data = './data/penn'
model = 'LSTM'
emsize = 200
nhid = 200
args=Args()
As #nbro suggested, the following command should work:
args = parser.parse_args(args=[])
In addition, if you have required arguments in your parser, set them inside the list:
args = parser.parse_args(args=['--req_1', '10', '--req_2', '10'])
Where you previously used:
import argparse
parser = argparse.ArgumentParser(description="Dummy parser")
parser.add_argument("--req_1", type=int, required=True, help="required int 1")
parser.add_argument("--req_2", type=int, required=True, help="required int 2")
You can also see from the notebook all params:
print("see all args:", args)
print("use one arg:", args.req_1)
You can find more information in the docs: Parsing arguments
An example is:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('echo')
args = parser.parse_args(['aa']) # actually you don't have to write (args=['aa'])
print(args.echo)
the output should be
>>> aa

Categories

Resources