Allow unknown arguments using argparse - python

I have a python script that requires the user to enter two arguments to run it, the arguments could be named anything.
I have also used argparse to allow the users to use a switch '-h' to get instructions of what is required to run the script.
The problem is that now I have used argparse I am getting an error when I pass my two randomly named arguments with the script.
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help',
help='To run this script please provide two arguments')
parser.parse_args()
currently when I run python test.py arg1 arg2 the error is
error: unrecognized arguments: arg1 arg2
I would like the code to allow the user to run test.py with a -h if required to see the instructions but also allow them to run the script with any two arguments as well.
Resolution with help tag to provide the user with context regarding the arguments required.
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help', help='To run this script please provide two arguments: first argument should be your scorm package name, second argument should be your html file name. Note: Any current zipped folder in the run directory with the same scorm package name will be overwritten.')
parser.add_argument('package_name', action="store", help='Please provide your scorm package name as the first argument')
parser.add_argument('html_file_name', action="store", help='Please provide your html file name as the second argument')
parser.parse_args()

Try the following code :-
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help',
help='To run this script please provide two arguments')
parser.add_argument('arg1')
parser.add_argument('arg2')
args, unknown = parser.parse_known_args()
All your unknown arguments will be parsed in unknown and all known in args.

import argparse
parser = argparse.ArgumentParser(description='sample')
# Add mandatory arguments
parser.add_argument('arg1', action="store")
parser.add_argument('arg2', action="store")
# Parse the arguments
args = parser.parse_args()
# sample usage of args
print (float(args.arg1) + float(args.arg2))

You need to add those arguments to the parser:
parser.add_argument("--arg1", "-a1", dest='arg1', type=str)
parser.add_argument("--arg2","-a2", dest='arg2', type=str)
If those arguments don't have the param required=true, you will be able to call the program without this arguments, so you can run the program with only the -h flag. To run the program with the arguments:
python test.py --arg1 "Argument" --arg2 "Argument"
Then, to have the arguments in variables you have to read them:
args = parser.parse_args()
argument1=args.arg1
argument2=args.arg2

Related

how to make python argparse to accept not declared argument

I have a script that receives online arguments using argparse, like this:
parser = argparse.ArgumentParser()
parser.add_argument(
"--local", action="store_true", help=("Write outputs to local disk.")
)
parser.add_argument(
"--swe", action="store_true", help=("Indicates 'staging' environment.")
)
args = parser.parse_args()
I want argparse to handle undeclared arguments and just to add them to the arguments dictionary, but it raises an error when I try python runner.py --local true --swe true --undeclared_argument this_is_a_test:
runner.py: error: unrecognized arguments: --undeclared_argument this_is_a_test

Positional argument for subparser raises the error: invalid choice

I am new to argsparse thus this might pretty sure be a newbie mistake so please bare with me. My code:
import argsparse
parent_parser = argparse.ArgumentParser(description='Argument Parser')
subparsers = parent_parser.add_subparsers(title="Sub-commands", description='Sub-commands Parser')
parser_create = subparsers.add_parser('run', parents=[parent_parser], add_help=False, help="run the program")
parser_create.add_argument('--program', metavar=('NAME'), required=True, type=str, help='name of the program')
This works perfectly fine when running parser.py run --program 'test' in the console:
args = parent_parser.parse_args(); print(args) outputs Namespace(program='test')
However, when I try to replace the optional argument with a positional one like:
parser_create.add_argument('program', metavar=('NAME'), type=str, help='name of the program')
And then run parser.py run 'test' in the console the following error is raised:
usage: parser.py run [-h] {run} ... NAME
parser.py run: error: invalid choice: 'test' (choose from 'run')
Adding the positional argument to a group results in the same error as above:
required = parser_create.add_argument_group('required positional argument')
required.add_argument('program', metavar=('NAME'), type=str, help='name of the program')
How can I pass positional arguments to the subparser formatted as run <program>?
I would appreciate any feedback. Thanks!
Thanks #PhilippSelenium for pointing out the link to the docs.
I solved this by removing parents=[parent_parser] from subparsers.add_parser()

combining argsparse and sys.args in Python3

I'm trying to write a command line tool for Python that I can run like this..
orgtoanki 'b' 'aj.org' --delimiter="~" --fields="front,back"
Here's the script:
#!/usr/bin/env python3
import sys
import argparse
from orgtoanki.api import create_package
parser = argparse.ArgumentParser()
parser.add_argument('--fields', '-f', help="fields, separated by commas", type=str, default='front,back')
parser.add_argument('--delimiter', '-d', help="delimiter", type= str, default='*')
args = parser.parse_args()
name=sys.argv[1]
org_src=sys.argv[2]
create_package(name, org_src, args.fields, agrs.delimiter)
When I run it, I get the following error:
usage: orgtoanki [-h] [--fields FIELDS] [--delimiter DELIMITER]
orgtoanki: error: unrecognized arguments: b aj.org
Why aren't 'b' and 'ab.org' being interpreted as sys.argv[1] and sys.argv[2], respectively?
And will the default work as I expect it to, if fields and delimiter aren't supplied to the command line?
The error here is caused by argparse parser which fails to apprehend the 'b' 'aj.org' part of the command, and your code never reaches the lines with sys.argv. Try adding those arguments to the argparse and avoid using both argparse and sys.argv simultaneously:
parser = argparse.ArgumentParser()
# these two lines
parser.add_argument('name', type=str)
parser.add_argument('org_src', type=str)
parser.add_argument('--fields', '-f', help="fields, separated by commas",
type=str, default='front,back')
parser.add_argument('--delimiter', '-d', help="delimiter",
type= str, default='*')
args = parser.parse_args()
You then can access their values at args.name and args.org_src respectively.
The default input to parser.parse_args is sys.argv[1:].
usage: orgtoanki [-h] [--fields FIELDS] [--delimiter DELIMITER]
orgtoanki: error: unrecognized arguments: b aj.org
The error message was printed by argparse, followed by an sys exit.
The message means that it found strings in sys.argv[1:] that it wasn't programmed to recognize. You only told it about the '--fields' and '--delimiter' flags.
You could add two positional fields as suggested by others.
Or you could use
[args, extras] = parser.parse_known_args()
name, org_src = extras
extras should then be a list ['b', 'aj.org'], the unrecognized arguments, which you could assign to your 2 variables.
Parsers don't (usually) consume and modify sys.argv. So several parsers (argparse or other) can read the same sys.argv. But for that to work they have to be forgiving about strings they don't need or recognize.

Pass a directory with argparse (no type checking needed)

I've written a file crawler and I'm trying to expand it. I want to use argparse to handle settings for the script including passing the starting directory in at the command line.
Example: /var/some/directory/
I have gotten several other arguments to work but I'm unable to pass this directory in correctly. I don't care if it's preceded by a flag or not, (e.g -d /path/to/start/) but I need to make sure that at the very least, this is argument is used as it will be the only mandatory option for the script to run.
Code Sample:
parser = argparse.ArgumentParser(description='py pub crawler...')
parser.add_argument('-v', '--verbose', help='verbose output from crawler', action="store_true")
parser.add_argument('-d', '--dump', help='dumps and replaces existing dictionaries', action="store_true")
parser.add_argument('-f', '--fake', help='crawl only, nothing stored to DB', action="store_true")
args = parser.parse_args()
if args.verbose:
verbose = True
if args.dump:
dump = True
if args.fake:
fake = True
Simply add:
parser.add_argument('directory',help='directory to use',action='store')
before your args = parser.parse_args() line. A simple test from the commandline shows that it does the right thing (printing args at the end of the script):
$ python test.py /foo/bar/baz
Namespace(directory='/foo/bar/baz', dump=False, fake=False, verbose=False)
$ python test.py
usage: test.py [-h] [-v] [-d] [-f] directory
test.py: error: too few arguments

argparse coding issue

write a script that takes two optional boolean arguments,"--verbose‚" and ‚"--live", and two required string arguments, "base"and "pattern". Please set up the command line processing using argparse.
This is the code I have so far for the question, I know I am getting close but something is not quite right. Any help is much appreciated.Thanks for all the quick useful feedback.
def main():
import argparse
parser = argparse.ArgumentParser(description='')
parser.add_argument('base', type=str)
parser.add_arguemnt('--verbose', action='store_true')
parser.add_argument('pattern', type=str)
parser.add_arguemnt('--live', action='store_true')
args = parser.parse_args()
print(args.base(args.pattern))
The string arguments are not required by default, so you need to state that. Also the print statement that uses the arguments is incorrect.
#!/usr/bin/python
import argparse
if __name__=="__main__":
parser = argparse.ArgumentParser(description='eg $python myargs.py --base arg1 --pattern arg2 [--verbose] [--live]')
parser.add_argument('--base', required=True, type=str)
parser.add_argument('--pattern', required=True, type=str)
parser.add_argument('--verbose', action='store_true')
parser.add_argument('--live', action='store_true')
args = parser.parse_args()
print "args.base=" + str(args.base)
print "args.pattern=" + str(args.pattern)
print "args.verbose=" + str(args.verbose)
print "args.live=" + str(args.live)
the #!/usr/bin/python at the top enables the script to be called directly, though python must be located there (to confirm, type $which python), and you must set the file to have execute permission ($chmod +x myargs.py)

Categories

Resources