i am new to work with python and i want to run this code , but get this error.
code:
import argparse
import os
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(BASE_DIR)
from model import *
import indoor3d_util
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', type=int, default=0, help='GPU to use [default: GPU 0]')
parser.add_argument('--batch_size', type=int, default=1, help='Batch Size during training [default: 1]')
parser.add_argument('--num_point', type=int, default=4096, help='Point number [default: 4096]')
parser.add_argument('--model_path', required=True, help='model checkpoint file path')
parser.add_argument('--dump_dir', required=True, help='dump folder path')
parser.add_argument('--output_filelist', required=True, help='TXT filename, filelist, each line is an output for a room')
parser.add_argument('--room_data_filelist', required=True, help='TXT filename, filelist, each line is a test room data label file.')
parser.add_argument('--no_clutter', action='store_true', help='If true, donot count the clutter class')
parser.add_argument('--visu', action='store_true', help='Whether to output OBJ file for prediction visualization.')
FLAGS = parser.parse_args()
what should i do?
error :
batch_test.py: error: the following arguments are required: --model_path, --dump_dir, --output_filelist, --room_data_filelist
Those arguments are defined as required in your code required=True but don't have a default specified. You can either specify them at runtime or you can add a default value or you can make them not required with required=False
If you need additional help with any of those options, let me know.
You should see something like:
usage: batch_test.py [-h] [--gpu GPU] [--batch_size BATCH_SIZE]
[--num_point NUM_POINT] --model_path MODEL_PATH
--dump_dir DUMP_DIR --output_filelist OUTPUT_FILELIST
--room_data_filelist ROOM_DATA_FILELIST [--no_clutter]
[--visu]
And just append the arguments from command line, e.g.
python batch_test.py --model_path PATH_TO_YOUR_MODEL, --dump_dir YOUR_DUMP_DIR, --output_filelist OUT_LIST, --room_data_filelist ROOM_DATA_LIST
Or turn off the required from your source code.
When running the python script you showed, you have to include the arguments that are required (which has required=True) in the following format:
python batch_test.py <argument 1> <argument 1 value> <argument 2> <argument 2 value> ...
In the code you showed, there are several arguments that are required, which are:--model-path, --dump_dir, --output_filelist, --room_data_filelist.
You can actually see the instruction on how to fill each argument by entering the command:
python batch_test.py -h
Related
I am training an AI but I am getting this error and cant figure out why.
usage: car.py [-h] [--dataset /path/to/car/dataset/] --weights /path/to/weights.h5 [--logs /path/to/logs/] [--image path or URL to image] [--video path or URL to video]
car.py: error: the following arguments are required: , --weights
this is my parser
if __name__ == '__main__':
import argparse
# Parse command line arguments
parser = argparse.ArgumentParser(
description='Train Mask R-CNN to detect cars.')
parser.add_argument("command",
metavar="<command>",
help="'train' or 'splash'")
parser.add_argument('--dataset', required=False,
metavar="/path/to/car/dataset/",
help='Directory of the Car dataset')
parser.add_argument('--weights', required=True,
metavar="/path/to/weights.h5",
help="Path to weights .h5 file or 'coco'")
parser.add_argument('--logs', required=False,
default=DEFAULT_LOGS_DIR,
metavar="/path/to/logs/",
help='Logs and checkpoints directory (default=logs/)')
parser.add_argument('--image', required=False,
metavar="path or URL to image",
help='Image to apply the color splash effect on')
parser.add_argument('--video', required=False,
metavar="path or URL to video",
help='Video to apply the color splash effect on')
args = parser.parse_args()
The error says that your weights argument is required, and you yourself have written so in your code. It won't run until you provide the argument --weights in your call
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('p', 'projectType', type=str, help = 'c or c++ project type', choices=['c', 'c++'])
parser.add_argument('i', 'inputfile', type=pathlib.Path, help = 'the input file path')
parser.add_argument('o',"outputfile",type=pathlib.Path, help= 'the output file path')
parser.add_argument
args = parser.parse_args()
when i run this code on command prompt, and enter the inputfile first for example.. it gives me an error. does Argparse have an option like getopt (where i call something with a letter before inputting it so no mix up ex, '-i ...input...'). Here this option is just for optional arguments.
Is there a way for positional arguments to do that?
As per the argparse documentation you would define it as an "optional" argument but with the required flag set to true, e.g.:
parser.add_argument('-i', '--inputfile', required=True, type=pathlib.Path, help='the input file path')
I'm trying to write a program for scraping images to create datasets to use for neural networks, however I'm getting a few problems
here's the code:
from imutils import paths
import argparse
import requests
import cv2
import os
ap = argparse.ArgumentParser()
ap.add_argument("-u", "--C:/Users/artus/datasets/urls.txt",
required=False, help="path containing URLs")
ap.add_argument("-o", "--C:/Users/artus/datasets/ShoesImage",
required=False, help="folder for downloaded images")
args = vars(ap.parse_args())
# grab the list of URLs from the input file, then initialize the
# total number of images downloaded thus far
rows = open(args["urls"]).read().strip().split("\n")
total = 0
when executed it should download all the images from the urls specified in the urls.txt file, however I'm getting this error:
Traceback (most recent call last):
File "C:/Users/artus/untitled5/imagescraping.py", line 16, in <module>
rows = open(args["urls"]).read().strip().split("\n")
KeyError: 'urls'
The second parameter of add_argument is the "long name" for the argument. For the first argument, you'll be passing --urls, and then argparse will make the value the user passes available as args["urls"]:
# ...
ap.add_argument("-u", "--urls", type=str,
required=False, help="path containing URLs")
Then, at the command line, pass in the argument:
python imagescraping.py --urls C:/Users/artus/datasets/urls.txt
Also, I don't think you need to wrap it in vars.
When I copy-n-paste your argparse code to a script:
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-u", "--C:/Users/artus/datasets/urls.txt",
required=False, help="path containing URLs")
ap.add_argument("-o", "--C:/Users/artus/datasets/ShoesImage",
required=False, help="folder for downloaded images")
args = ap.parse_args()
print(args)
and call it without arguments:
0923:~/mypy$ python3 stack56745387.py
Namespace(**{'C:/Users/artus/datasets/ShoesImage': None, 'C:/Users/artus/datasets/urls.txt': None})
and asking for help:
1743:~/mypy$ python3 stack56745387.py -h
usage: stack56745387.py [-h] [-u C:/USERS/ARTUS/DATASETS/URLS.TXT]
[-o C:/USERS/ARTUS/DATASETS/SHOESIMAGE]
optional arguments:
-h, --help show this help message and exit
-u C:/USERS/ARTUS/DATASETS/URLS.TXT, --C:/Users/artus/datasets/urls.txt C:/USERS/ARTUS/DATASETS/URLS.TXT
path containing URLs
-o C:/USERS/ARTUS/DATASETS/SHOESIMAGE, --C:/Users/artus/datasets/ShoesImage C:/USERS/ARTUS/DATASETS/SHOESIMAGE
folder for downloaded images
You probably intended the "--C:/Users/artus/datasets/urls.txt" to be something like the default value, but you defined it as the long flag and dest for the argument. (Nothing in your setup specified urls as the desired dest or key.)
which you'd have to use as:
1750:~/mypy$ python3 stack56745387.py --C:/Users/artus/datasets/urls.txt foobar
Namespace(**{'C:/Users/artus/datasets/ShoesImage': None, 'C:/Users/artus/datasets/urls.txt': 'foobar'})
Changing the code to:
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-u", "--urls", default="C:/Users/artus/datasets/urls.txt",
required=False, help="path containing URLs (default: %(default)s)")
ap.add_argument("-o", "--images",default="C:/Users/artus/datasets/ShoesImage",
required=False, help="folder for downloaded images (default: %(default)s)")
args = ap.parse_args()
print(args)
1802:~/mypy$ python3 stack56745387.py -h
usage: stack56745387.py [-h] [-u URLS] [-o IMAGES]
optional arguments:
-h, --help show this help message and exit
-u URLS, --urls URLS path containing URLs (default:
C:/Users/artus/datasets/urls.txt)
-o IMAGES, --images IMAGES
folder for downloaded images (default:
C:/Users/artus/datasets/ShoesImage)
1803:~/mypy$ python3 stack56745387.py --urls foobar
Namespace(images='C:/Users/artus/datasets/ShoesImage', urls='foobar')
Now you could use args.urls or vars(args)['urls'].
I'm trying to build a script that uses subparsers arguments. However, I can not pass any of the sub-arguments as a parameter. Resulting in "invalid choice:" for any input combination.
Example input:
python3 preprocess.py -d ../data/acm/ tf -l en
Complete Output:
usage: preprocess.py [-h] [-k FOLDS] -d DATASETDIR [DATASETDIR ...] {tf} ...
preprocess.py: error: invalid choice: 'en' (choose from 'tf')
The code is
parser = argparse.ArgumentParser(description='Split input dataset into k folds of cross-validation.')
parser.add_argument('-k', '--folds', default=10, help='Number of folds for K fold cross-validation.', type=int)
required_args = parser.add_argument_group('required arguments')
required_args.add_argument('-d','--datasetdir', type=str, nargs='+', help='Dataset path (For more info: readme.txt)', required=True)
parser_subparsers = parser.add_subparsers(title="Representations", description="Choose the representations")
parser_tf = parser_subparsers.add_parser('tf', help='TF helper')
parser_tf.add_argument('-l', '--language', type=str, help='Language', default='en', choices=['en'])
parser_tf.add_argument('-s', '--stopword', type=bool, help='Skip stopwords', default=True)
args = parser.parse_args()
Since --datasetdir has nargs="+" the other argument(s) are being slurped up as additional dataset dir, rather than invoking the subparser.
CLI suggestion: change datasetdir into a plain old positional argument, with ability to separate paths using os.pathsep. It will be difficult to wrangle argparse into what you wanted to do, and using optional arguments with required=True is a code smell in the first place.
New interface will look something like this:
python3 preprocess.py ../data/acm/:/dir2:/dir3 tf -l en
Running python 2.7.5 in Spyder, trying to set up an argument parser to import input from a file called data.csv in the same folder as my script. Currently, this part of my function looks like so:
from sys import argv
from argparse import ArgumentParser
def ParseArguments():
parser = ArgumentParser(description='Description of program')
parser.add_argument("-f", type=str, dest="data",
default="", help="Input file", required=True)
parser.add_argument("-o", type=str, dest="output_file",
default="", help="Output file")
parser.add_argument("-p", type=float, dest="first_parameter",
default=0.5, help="First Parameter (decimal)")
parser.add_argument("-n", type=int, dest="second_parameter",
default=0, help="Second Parameter (integer)")
args = parser.parse_args()
def my_function(args):
print "Input file is:", args.data
print "Output file is:", args.output_file
print "Parameter 1 is:", args.first_parameter
print "Parameter 2 is:", args.second_parameter
Then I call it in my main function:
def main(argv):
args = ParseArguments()
my_function(args)
args.data
def read(data):
fh = read(args.data, "data")
(...)
Now, when I try to run this I get the error message:
runfile('C:filepath', wdir='C:/filepath')
usage: code.py [-h] -f DATA [-o OUTPUT_FILE] [-p FIRST_PARAMETER]
[-n SECOND_PARAMETER]
code.py: error: argument -f is required
I can't comprehend how this is not defined - there is a file called data in the working directory, and from my understanding of the argument parser it doesn't care about file types when assigning input, so it should be assigning my data.csv as input. What gives?
Another option might be to just not use the argument parser, of course, and reading the file directly by commands, but I'd like to understand what I've done wrong here all the same.