I'm running this as part of a call to the api using the url. I dont know what I'm doing wrong - the terminal keeps saying I have an Attribute error where the 'Namespace' object has no attribute to offset. I wanted to add search parameters "offset, sort and category_filter", but am not sure what I have to do to the parser.add_argument. I tried copying those that were in the sample code listed below, but it didnt seem to work. I'm a bit confused as to why that is...
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-q', '--term', dest='term', default=DEFAULT_TERM,
type=str, help='Search term (default: %(default)s)')
parser.add_argument('-l', '--location', dest='location',
default=DEFAULT_LOCATION, type=str,
help='Search location (default: %(default)s)')
parser.add_argument('--offset', dest='offset', default=DEFAULT_OFFSET,
type=int, help='Search offset (default: %(default)s)')
parser.add_argument('--sort', dest='sort', default=DEFAULT_SORT,
type=int, help='Sear sort (default:%(default)s)')
parser.add_argument('--category_filter', dest='category_filter', default=DEFAULT_CATEGORY_FILTER,
type=str, help='Search category_filter (default: %(default)s)')
input_values = parser.parse_args()
try:
query_api(input_values.term, input_values.location, input_values.offset, input_values.sort, input_values.category_filter)
except urllib2.HTTPError as error:
Related
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
conflict_handler(action, confl_optionals)
File "/usr/local/lib/python3.6/argparse.py", line 1510, in _handle_conflict_error
raise ArgumentError(action, message % conflict_string)
argparse.ArgumentError: argument -h/--height: conflicting option string: -h
The above is the error message,
here is my code,
I don't see the error:
# 1) Parse the arguments
parser = argparse.ArgumentParser(description="Description for my parser")
parser.add_argument("-v", "--velocity", action="store", required=True, help="The velocity of the object is required")
parser.add_argument("-a", "--angle", action="store", type=float, required=True, help="The angle of the object is required")
parser.add_argument("-h", "--height", required=False, default= 1.2, help="The height of the object is not required. Default is set to 1.2 meters" )
Option "-h" is by default predefined as a "help" option, which prints the description and the list of arguments. Your custom "-h --height" conflicts with this, thus causing an error.
It wouldn't be nice to overwrite the default "-h --help" option, because many users expect "-h" option to print help message. (So if I were you I would find another way to name the option.) But you can ignore it if you really need to by using add_help parameter with the constructor. Like this:
parser = argparse.ArgumentParser(description="Description for my parser", add_help=False)
If you want to keep "--help" option, you have to add another line of parser.add_argument("--help", action="help"). (Thanks to chepner)
As the error suggests you are using a param name who is conflicting with other. Particularly in this case the -h option. The lib argparse always include the -h option to print the script help, so for the height, you must use a different param than -h, for example -ht.
parser = argparse.ArgumentParser(description="Description for my parser")
parser.add_argument("-v", "--velocity", action="store", required=True, help="The velocity of the object is required")
parser.add_argument("-a", "--angle", action="store", type=float, required=True, help="The angle of the object is required")
parser.add_argument("-ht", "--height", required=False, default= 1.2, help="The height of the object is not required. Default is set to 1.2 meters" )
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
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.
I need to view the complete string in the Argparse object args.networkModel
Original code is from https://github.com/cmusatyalab/openface/blob/master/demos/classifier.py
I only have access to the pdb in the terminal.
When I try the print(args.networkModel) I get
/home/aanilil/ml/openface/demos/../models/openargs.networkModelface/nn4.small2.v1.t7
Is there a way to Print the complete string?
I have also tried the pprint(args.networkModel)
Where I get the output
*** TypeError: 'module' object is not callable
The original parser is constructed like so
parser = argparse.ArgumentParser()
parser.add_argument(
'--dlibFacePredictor',
type=str,
help="Path to dlib's face predictor.",
default=os.path.join(
dlibModelDir,
"shape_predictor_68_face_landmarks.dat"))
parser.add_argument(
'--networkModel',
type=str,
help="Path to Torch network model.",
default=os.path.join(
openfaceModelDir,
'nn4.small2.v1.t7'))
parser.add_argument('--imgDim', type=int,
help="Default image dimension.", default=96)
parser.add_argument('--cuda', action='store_true')
parser.add_argument('--verbose', action='store_true')
subparsers = parser.add_subparsers(dest='mode', help="Mode")
trainParser = subparsers.add_parser('train',
help="Train a new classifier.")
trainParser.add_argument('--ldaDim', type=int, default=-1)
trainParser.add_argument(
'--classifier',
type=str,
choices=[
'LinearSvm',
'GridSearchSvm',
'GMM',
'RadialSvm',
'DecisionTree',
'GaussianNB',
'DBN'],
help='The type of classifier to use.',
default='LinearSvm')
trainParser.add_argument(
'workDir',
type=str,
help="The input work directory containing 'reps.csv' and 'labels.csv'. Obtained from aligning a directory with 'align-dlib' and getting the representations with 'batch-represent'.")
inferParser = subparsers.add_parser(
'infer', help='Predict who an image contains from a trained classifier.')
inferParser.add_argument(
'classifierModel',
type=str,
help='The Python pickle representing the classifier. This is NOT the Torch network model, which can be set with --networkModel.')
inferParser.add_argument('imgs', type=str, nargs='+',
help="Input image.")
inferParser.add_argument('--multi', help="Infer multiple faces in image",
action="store_true")
args = parser.parse_args()