Overwrite a default argument with another one using the command line - python

can anyone help me to overwrite a default argument with another one passing through the command line ?
this is my code:
parser = argparse.ArgumentParser()
parser.add_argument('log', action='store', help='path to the log file')
parser.add_argument('-f', '--filter', default =['filter.json'], help='path to a filter file')
parser.add_argument('-w', '--waiver', type =list, default = [], action='append', help='path to a waiver file')
args = parser.parse_args()
this is the command line to be used:
python3 script.py -f filter_file -w waiver_file log_file
so, I need to overwrite this default =['filter.json'] with filter_file
But don't know what should I do, can you support please ?
thanks

Your script is working:
My output:
PS C:\Users\xf01145\Documents\Python> & "C:/Program Files/Python37/python.exe"
c:/Users/xf01145/Documents/Python/cli.py log.log -f bla.bla blubb.bla test.test hugo.txt
Namespace(filter=['bla.bla', 'blubb.bla', 'test.test', 'hugo.txt'], log='log.log', waiver=[])
0 bla.bla
1 blubb.bla
2 test.test
3 hugo.txt
PS C:\Users\xf01145\Documents\Python>
from this:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('log', action='store', help='path to the log file')
parser.add_argument('-f', '--filter', default =['filter.json'], help='path to a filter file', nargs='+')
parser.add_argument('-w', '--waiver', type =list, default = [], action='append', help='path to a waiver file')
args = parser.parse_args()
print(args)
for i,item in enumerate(args.filter):
print(i, item)

Related

Arguments in top level parser come before subparsers if it has subparsers

I have this MRE:
import argparse
parser = argparse.ArgumentParser(description='Bundle a Python application')
parser.add_argument(
'-o', '--output', metavar='OUTPUT FILE', dest='file_name', type=str,
default=None)
parser.add_argument(
'--extensions', '--ext', action='store_const', metavar='EXTENSIONS',
dest='extensions', const=True, default=False,
help='Whether to allow the importing of C extensions (not needed if C extensions are optional')
if 0:
actions_parser = parser.add_subparsers(
dest='action', metavar='ACTION', help='Action mod should take')
actions_parser.required = True
build_parser = actions_parser.add_parser("build")
build_parser.add_argument(
dest='root', metavar='PROJECT', type=str, help='Project path',
nargs='?', default='.')
get_parser = actions_parser.add_parser("get")
get_parser.add_argument(
dest='module', metavar='MODULE', type=str, help='Module to download')
args = parser.parse_args()
If you run this with python test.py --ext, this works as expected.
However, if you change the 0 to a 1, then python test.py foo --ext fails, even though it should work. Why?
As it turns out, all the arguments attached to the main parser must be before any subaction, e.g. python test.py --ext foo.

Unable to assign default values to arguments in Python argparse

I am using Python argparse to take in parameters through the CLI. I have tried using the following but when I don't give any one of the arguments, it gives the output as None. I want then default ones to be the ones provided in const=. Please take a look.
parser = argparse.ArgumentParser()
parser.add_argument('--input', nargs='?', const='testInput')
parser.add_argument('--target', nargs='?', const='testTarget')
parser.add_argument('--msg', nargs='?', const='helloFromTheOtherSide')
args = parser.parse_args()
print args.input
If I don't give input, it prints it as None as I said. I want it to print TestInput instead..
Use the default argument:
parser = argparse.ArgumentParser()
parser.add_argument('--input', nargs='?', default='testInput')
parser.add_argument('--target', nargs='?', default='testTarget')
parser.add_argument('--msg', nargs='?', default='helloFromTheOtherSide')
args = parser.parse_args()
print args.input
With
parser.add_argument('--input', nargs='?', default='testInput', const='aConst')
you have a 3 way choice
prog # input='testInput'
prog --input # input='aConst'
prog --input myfile # input='myfile'
If you don't need that aConst option, omit the nargs='?'. Since it is a flagged argument it is already optional. It doesn't need the `?'.
parser.add_argument('--input', default='testInput')

Error with argparse

I'm having some issues with getting argparse to run correctly. Previously, my script would be run as follows:
script.py <input_file(s)> <output_filename>
With code that looked like this:
cell_list_input = sys.argv[1:]
cell_list_output = sys.argv[len(cell_list_input)]
cell_list_input = cell_list_input[:len(cell_list_input)-1]
However, I'd like to add some argument parsing just to make it more readable and usable. Ideally, the format would be similar with the following options:
script.py -i <input_file(s)> -o <output_filename>
script.py --input_list <input_file(s)> --output <output_filename>
The argparse equivalent I'm trying to implement looks like this right now:
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input_list', action='append', dest='input_list', default=[], help='Input list of cell names')
parser.add_argument('-o', '--output', action='store', dest='output', help='Output file destination/name')
cli = parser.parse_args()
I know I'm doing something wrong, but can't seem to figure out what. Any help is appreciated. Thanks!
You need to specify nargs for your input file list. Try this:
parser.add_argument('-i', '--input_list', nargs="+", action='append', dest='input_list', default=[], help='Input list of cell names')
Complete example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input_list', nargs="+", default=[], help='Input list of cell names')
parser.add_argument('-o', '--output', help='Output file destination/name')
cli = parser.parse_args()
print cli
Result:
$ python i.py -i a
Namespace(input_list=['a'], output=None)
$ python i.py -i a b c -o d
Namespace(input_list=['a', 'b', 'c'], output='d')

argparse combine with optional parameter

If the user use the optional parameter -o then the user has to use parameter -b as well.
However, the -b parameter you have to use only if the user set the parameter -o.
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-f', nargs='?', required=True)
parser.add_argument('-o', nargs='?', required=False)
parser.add_argument('-b', nargs='?', required=????)
args = parser.parse_args()
How is it possible to solve this problem?
Add a test after args = parser.parse_args():
if args.o and not args.b:
print >> sys.stderr, 'The -b option is required whenever -o is specified'
sys.exit(1)

Set and require default Python script OptionParser

The following "parser.add_option" statements work but if the script is run without an option/arg it will not complain. If an option/argument are not specified I would like it to display help (-h / --help) as default.
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option('-d', '--directory',
action='store', dest='directory',
default=None, help='specify directory')
parser.add_option('-f', '--file',
action='store', dest='filename',
default=None, help='specify file')
parser.add_option('-v', '--version',
action="store_true", dest="show_version",
default=False, help='displays the version number')
(options, args) = parser.parse_args()
#if len(args) < 1:
# parser.error("incorrect number of arguments")
Secondly, if I enable the following snip than I get "error: incorrect number of arguments" even when specifying an option/arg.
if len(args) < 1:
parser.error("incorrect number of arguments")
Thanks.
Updated Code with Traceback error below
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option('-d', '--directory',
action='store', dest='directory',
default=None, help='specify directory')
parser.add_option('-f', '--file',
action='store', dest='filename',
default=None, help='specify file')
parser.add_option('-v', '--version',
action="store_true", dest="show_version",
default=False, help='displays the version number')
if len(sys.argv) == 1:
parser.print_help()
sys.exit()
(options, args) = parser.parse_args()
#if options.show_version:
# prog = os.path.basename(sys.argv[0])
# version_str = "1.0"
# print "version is: %s %s" % (prog, version_str)
# sys.exit(0)
filenames_or_wildcards = []
# remove next line if you do not want allow to run the script without the -f -d
# option, but with arguments
filenames_or_wildcards = args # take all filenames passed in the command line
# if -f was specified add them (in current working directory)
if options.filename is not None:
filenames_or_wildcards.append(options.filename)
Traceback
$ python boto-backup.py Traceback (most recent call last): File "boto-backup.py", line 41, in <module>
filenames_or_wildcards = args # take all filenames passed in the command line NameError: name 'args' is not defined
I would do something like this:
from optparse import OptionParser
import sys
def main():
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
parser.add_option('-d', '--directory',
action='store', dest='directory',
default=None, help='specify directory')
parser.add_option('-f', '--file',
action='store', dest='filename',
default=None, help='specify file')
parser.add_option('-v', '--version',
action="store_true", dest="show_version",
default=False, help='displays the version number')
if len(sys.argv) == 1:
parser.print_help()
sys.exit()
(options, args) = parser.parse_args()
# rest of program...
if __name__ == '__main__':
main()
So we set up the parser and options, and then check if there was any command-line input.
If none, we print the help message and exit. Otherwise we proceed with program execution.
When run with no command-line arguments the output is:
Usage: your_script_name_here.py [options] arg
Options:
-h, --help show this help message and exit
-d DIRECTORY, --directory=DIRECTORY
specify directory
-f FILENAME, --file=FILENAME
specify file
-v, --version displays the version number
Edit (in response to updated code):
Whitespace/indentation is important in Python.
Make sure that the rest of your code is indented such that it belongs to the main() function.
From filenames_or_wildcards = [] on, your code is outside of the scope of the main() function and thus doesn't have a variable named args.

Categories

Resources