Running Argpars but got this error SystemExit 2 - python

I am trying to set up training arguments and parse but I got this error could anyone help please!
parser = argparse.ArgumentParser(description='Explore pre-trained AlexNet')
parser.add_argument(
'--image_path', type=str,
help='Full path to the input image to load.')
parser.add_argument(
'--use_pre_trained', type=bool, default=True,
help='Load pre-trained weights?')
args = parser.parse_args()
got this error
usage: ipykernel_launcher.py [-h] [--image_path IMAGE_PATH]
[--use_pre_trained USE_PRE_TRAINED]
ipykernel_launcher.py: error: unrecognized arguments: -f /root/.local/share/jupyter/runtime/kernel-ff8e2476-e39b-4e40-b8f9-6b8113fe8f1f.json
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2

In a Jupyter notebook cell:
import sys
sys.argv
I get get
['/usr/local/lib/python3.8/dist-packages/ipykernel_launcher.py',
'-f',
'/home/paul/.local/share/jupyter/runtime/kernel-7923bfd2-9f96-45cf-8b44-1859a2185715.json']
The Jupyter server is using the sys.argv to set up the communication channel with your kernel. argparse parses this list too.
So commandline and argparse cannot be used to provide arguments to your notebook when run this way.
How did you start this script? Did you even try to provide the commandline values that the script expected?
'--image_path'
'--use_pre_trained'
If you did, you probably would have gotten a different parser's error, about 'unexpected arguments'. That's coming from the server.

If you use a Colab may this solution help you, this solution suggest to you to write argparse in the other python file introduction-argparse-colab
%%writefile parsing.py
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

In a Jupyter notebook code works like this:
parser = argparse.ArgumentParser()
parser.add_argument('--image_folder', type=str, default='/content/image', help='path to image folder')
parser.add_argument("-f", "--file", required=False)
You need to add in the end of " parser.add_argument " line ( This is the reason you are getting 'SystemExit: 2' error ):
parser.add_argument("-f", required=False)
in your case this should work:
parser = argparse.ArgumentParser(description='Explore pre-trained AlexNet')
parser.add_argument('--image_path', type=str, default='your_path', help='Full path to the input image.')
parser.add_argument('--use_pre_trained', type=bool, default=True, help='Load pre-trained weights?')
parser.add_argument("-f", "--file", required=False)
args = parser.parse_args()
Now you can call:
image = args.image_path
Or
from PIL import Image
image = Image.open(args.image_path)
Tested in Google colab

Related

Argparse: exception for option required=True

I use the following code to parse argument to my script (simplified version):
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-l", "--library", required=True)
ap.add_argument("--csv2fasta", required=False)
args = vars(ap.parse_args())
For every way the script can be run, the -l/--library flag should be required (required=True), but is there a way that it can use the setting required=False when you only use the --csv2fasta flag?
You have to write your test after parsing arguments, here's what I do for such cases:
def parse_args():
ap = argparse.ArgumentParser()
ap.add_argument("-l", "--library")
ap.add_argument("--csv2fasta")
args = ap.parse_args()
if not args.library and not args.csv2fasta:
ap.error("--library is required unless you provide --csv2fasta argument")
return args
$ python3 test-args.py
usage: test-args.py [-h] [-l LIBRARY] [--csv2fasta CSV2FASTA]
test-args.py: error: --library is required unless you provide --csv2fasta argument
$ python3 test-args.py --csv2fasta value

How to parse arguments in python (spyder)?

I am following this tutorial and trying to run the below part of the script. I am using python 3.7 and spyder 3.3.4.
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True,
help="path to input dataset (i.e., directory of images)")
ap.add_argument("-m", "--model", required=True,
help="path to output model")
ap.add_argument("-l", "--labelbin", required=True,
help="path to output label binarizer")
ap.add_argument("-p", "--plot", type=str, default="plot.png",
help="path to output accuracy/loss plot")
args = vars(ap.parse_args())
I have tried going to Run > Configuration per file and entering the arguments as advised by this post and and this post.
command line options: path1, path2, path3, path4
I filled out the appropriate paths for the arguments above and then ran the script, but go the error below.
usage: train.py [-h] -d DATASET -m MODEL -l LABELBIN [-p PLOT]
train.py: error: the following arguments are required: -d/--dataset,
-m/--model, -l/--labelbin An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
How can I fix this error to run my script appropriately and pass the arguments in spyder?
You can parse arguments by doing a special run from the settings and putting in the order that the arguments are expected.

Solving of the arguments

After running the code, the error is as follows:
usage: text-summarizer.py [-h] [-l LENGTH] filepath
text-summarizer.py: error: the following arguments are required: filepath
I want to solve this issue by knowing how to input the file name to this piece of code mentioned :
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("filepath", help="File name of text to summarize")
parser.add_argument(
"-l", "--length", default=4, help="Number of sentences to return"
)
args = parser.parse_args()
return args
When you run the code from the console just write
python text-summarizer.py 'path/to/file'
or if you use python3:
python3 text-summarizer.py 'path/to/file'
where `path/to/file' is actually the path (on your computer) that you want to summarize

ConfigArgParse throwing unrecognized arguments with default config.ini

as far as I understood, with ConfigArgParse, I can set the very main config in a config.ini file of my program and make some of those choices available via command line. However, when I set my config.ini file as default in the constructor, I get the following error:
main.py: error: unrecognized arguments: --input_base data
where --input_base is the only configuration not included in my parser as can be seen in the following:
parser = ArgParser(default_config_files=['config.ini'])
parser.add_argument('-out', '--output_base', type=str, help='xyz')
parser.add_argument('--amount', type=int, help='xyz')
parser.add_argument('--num_jobs', help='xyz')
parser.add_argument('--batch_size', type=int, help='xyz')
parser.add_argument('--queue_size', type=int, help='xyz')
parser.add_argument('--kind', choices={'long', 'short', 'both'}, help='xyz')
parser.add_argument('--level', choices={'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'}, help='xyz')
config = parser.parse_args()
Only using config.ini works fine but because of usability I have to include command line args as well.
Thanks for your help. Appreciate it!
Try change last line to:
config, unknown = parser.parse_known_args()
This will parse only known arguments (ignoring every unknown).
as in this question: Python argparse ignore unrecognised arguments

Python ArgumentParser - Error - Missing arguments?

I'm trying to run this code :
ap = argparse.ArgumentParser()
ap.add_argument("-q", "--query", required=True, help="search query to search Bing Image API for")
ap.add_argument("-o", "--output", required=True, help="path to output directory of images")
args = vars(ap.parse_args())
And I get this error :
usage: ipykernel_launcher.py [-h] -q QUERY -o OUTPUT
ipykernel_launcher.py: error: the following arguments are required:
-q/--query, -o/--output
I've tried to look into the ArgumentParser documentation (here), but couldn't find my answer. Could someone help me ?
You must launch the application providing the arguments indicated in the error message. In your code, both arguments are required. Hence, you must supply them to run the application.
Here is what it may be expecting
python ipykernel_launcher.py -q "<query>", -o "<dir>"
Note, the <query> and <dir> above are fillers. You must provide a query inline with applications definition of a query. The -o flag indicates a requirement to pass a directory. Hence, it could be as simple as ./output or something between these lines.
You set the required option to true:
ap.add_argument("-q", "--query", **required=True,** help="search query to search Bing Image API for")
ap.add_argument("-o", "--output", **required=True**, help="path to output directory of images")
(** added for visibility)
writing
ap.add_argument("-q", "--query", **required=False,** help="search query to search Bing Image API for")
ap.add_argument("-o", "--output", **required=False**, help="path to output directory of images")
instead, should fix the problem. Unless of course you want them to be required, then you have to call the script with the arguments.

Categories