How can I parse flags in command line argument? - python

I have to implement a --pos flag in Python and create a new condition if it exists, but argparse does not recognize it when I enter it in the command line argument.
parser = argparse.ArgumentParser()
parser.add_argument('lang', type=str, help='Language')
parser.add_argument('mode', help='the mode you want to output the results with')
parser.add_argument('flag', help='the flag that triggers pos-tags')
args = parser.parse_args()
So when I run the command:
python3 pi.py en lemma --pos
I get the following error message:
error: unrecognized arguments: --pos
Is there a way to catch that flag as a third argument?

In your code you are defining a "positional argument" which is not what you want. If you want to implement a flag (true/false) --pos just do that.
...
parser.add_argument('--pos', action='store_true', help='the flag that triggers pos-tags')
args = parser.parse_args()
if args.pos:
...
and call it as
python3 pi.py en lemma --pos

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

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.

Allow unknown arguments using argparse

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

`argparse` multiple choice argument?

I am using argparse to parse the Python command line which is supposed to look like this:
python script_name.py --sdks=first, second
My script looks like this:
sdk_choises = ['aio','sw']
parser = argparse.ArgumentParser(description='Blah blah')
parser.add_argument('--sdks', action='append', nargs='+', required=True, help='specifies target SDK(s)')
args = parser.parse_args()
if 'aio' in args.sdks:
# do something with aio
if 'sw' in args.sdks:
# do something with sw
When I execute:
python script_name.py --sdks=aio, sw I get error:
"usage: script.py [-h] --sdks SDKS [SDKS ...]
build.py: error: unrecognized arguments: sw"
I'd like to be able to choose one or all choices:
python script_name.py --sdks=first
python script_name.py --sdks=second
python script_name.py --sdks=first, second
Where did I go wrong?
The following works nice:
import argparse
parser = argparse.ArgumentParser(description='Blah blah')
parser.add_argument('--sdks', nargs='+', required=True, help='specifies target SDK(s)')
args = parser.parse_args()
print(args.sdks)
You don't need the = when passing options, just use:
$ python test.py --sdks ai pw
['ai', 'pw']
If you prefer your original form of the comma-separated list, plus check if the argument is valid, then I recommend:
parser.add_argument('--sdks', nargs=1, type=lambda s: [sdk_choises[sdk_choises.index(f)] for f in s.split(',')], ...
Even cleaner way is to define it in a separate function similar to lambda above:
parser.add_argument('--sdks', nargs=1, type=my_parse_function, ...
argparse docs has examples for the parsing function with proper error reporting.
With nargs=1 you'd need to remove one extra list layer.

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

Categories

Resources