I am bundling my python app into an .AppImage file. Now, when I run it with flag -h I would expect it to print something along these lines:
$ ./mytool.AppImage -h
usage: mytool [-h] [-d DIR] [-f] [-e] [BLA [BLA ...]]
...
But due to the nature of the AppImage bundling process I get:
$ ./mytool.AppImage -h
usage: AppRun [-h] [-d DIR] [-f] [-e] [BLA [BLA ...]]
...
That is, AppRun instead of mytool.
So my question is:
How can I force override the app name so that regardless of how the app is called it will always print the same name in the usage string?
As per hpaulj's comment, this can solved by simply setting the prog parameter of the argparse.ArgumentParser constructor:
parser = argparse.ArgumentParser(
prog='mytool',
description='Some description...'
)
Related
I am using argparse with subparsers to do different actions. Each action has slightly different arguments.
I have set it up as the documentations instructs, with one action in subparser (parser_2) and the other subparser (parser_3) when i do help for usage of each it says the correct parameters
This is for cdf:
positional arguments:
repo name the repo to perform tasks on
optional arguments:
-h, --help show this help message and exit
--state {open,closed}
Print issues in a repository having status of
all(default), open, or closed
this is for clsiss:
usage: subparsprob.py clsiss [-h] repo issnums [issnums ...]
positional arguments:
repo name the repo to perform tasks on
issnums put the issue number(s) separated by blank
optional arguments:
-h, --help show this help message and exit
however when i actually run the commands i get usage errors:
for clsiss executing from command line:
PS C:\xxx> python subparsprob.py clsiss repo 1
usage: subparsprob.py clsiss [-h] repo issnums [issnums ...]
subparsprob.py clsiss: error: argument issnums: invalid int value: 'repo'
for cdf (executing from command line):
PS C:\xxx> python subparsprob.py cdf repo
usage: subparsprob.py clsiss [-h] repo issnums [issnums ...]
subparsprob.py clsiss: error: argument issnums: invalid int value: 'repo'
please help, I am using the correct arguments and number of argument but cannot figure out why the usage is wrong when i actually try to run it
i am still getting the same error , here is the entire code, I cannot figure it out. Please help
#!/usr/bin/python3
import argparse
import sys
import os
argv = sys.argv[1:]
# from issueGithub import IssueGithub, Taskname
def main():
parser=argparse.ArgumentParser(description='Invoke various github
actions')
subparsers = parser.add_subparsers(help='sub-commands for Github
options',dest='action_name')
parser_2 =subparsers.add_parser('clsiss',help='close issues')
parser_2.add_argument('repo',type=str,help="name the repo to perform
tasks
on")
parser_2.add_argument('issnums',type=int,nargs='+',help="put the issue
number(s) separated by blank")
parser_3 = subparsers.add_parser('cdf',help='create default
tasks/issues')
parser_3.add_argument('repo',type=str,help="name the repo to perform
tasks
on")
parser_3.add_argument('--state',choices=['open','closed'], default='all',
help='Print issues in a repository
args = parser.parse_args()
args2 = parser_2.parse_args()
args3 = parser_3.parse_args()
print("Args are")
print(args)
print(args2)
print(args3)
if __name__ =="__main__":
main()
With a copy-n-paste of your code:
1301:~/mypy$ python3 stack58684096.py -h
usage: stack58684096.py [-h] {clsiss,cdf} ...
Invoke various actions
positional arguments:
{clsiss,cdf} sub-commands for options
clsiss close issues
cdf create default tasks/issues
optional arguments:
-h, --help show this help message and exit
I don't get your errors:
1302:~/mypy$ python3 stack58684096.py clsiss repo 1
Namespace(action_name='clsiss', issnums=[1], repo='repo')
1302:~/mypy$ python3 stack58684096.py cdf repo
Namespace(action_name='cdf', repo='repo', state='all')
1302:~/mypy$ python3 stack58684096.py clsiss -h
usage: stack58684096.py clsiss [-h] repo issnums [issnums ...]
positional arguments:
repo name the repo to perform tasks on
issnums put the issue number(s) separated by blank
optional arguments:
-h, --help show this help message and exit
Your errors - sort of:
1302:~/mypy$ python3 stack58684096.py clsiss repo
usage: stack58684096.py clsiss [-h] repo issnums [issnums ...]
stack58684096.py clsiss: error: the following arguments are required: issnums
1304:~/mypy$ python3 stack58684096.py clsiss repo repo
usage: stack58684096.py clsiss [-h] repo issnums [issnums ...]
stack58684096.py clsiss: error: argument issnums: invalid int value: 'repo'
I'm running Python unittest using the discover mode:
% python -m unittest discover
The system prints a dot for each test, but I'd rather see a test name.
Is there an option that makes this happen?
The verbose flag (-v) is what you're looking for:
$ python -m unittest discover -v
test_a (tests.test_a.TestA) ... ok
test_b (tests.test_b.TestB) ... ok
...
For more options, check:
$ python -m unittest --help
usage: python -m unittest [-h] [-v] [-q] [--locals] [-f] [-c] [-b]
[tests [tests ...]]
positional arguments:
tests a list of any number of test modules, classes and test
methods.
optional arguments:
-h, --help show this help message and exit
-v, --verbose Verbose output
-q, --quiet Quiet output
--locals Show local variables in tracebacks
-f, --failfast Stop on first fail or error
-c, --catch Catch Ctrl-C and display results so far
-b, --buffer Buffer stdout and stderr during tests
...
Hi I'm using ArgParse to handle my arguments. I would like the code to work like this
# Main function
$ myApp -i INPUT -o OUTPUT -s STUFF
# Configure function
$ myApp config -a conf1 -b conf2
import argparse
from argparse import RawTextHelpFormatter
parser = argparse.ArgumentParser(description='myApp',formatter_class=RawTextHelpFormatter)
parser.add_argument('-i',help='input',required=True)
parser.add_argument('-o',help='output',required=True)
parser.add_argument('-s',help='stuff',default=None,required=False)
args = parser.parse_args()
subp = parser.add_subparsers()
conf_parser = subp.add_parser('config', help='configure')
conf_parser.add_argument('-a',help='a config file',default=None,required=False)
conf_parser.add_argument('-b',help='b config file',default=None,required=False)
conf_args = conf_arser.parse_args()
Here's the output
python sandbox/test1.py --help
usage: test1.py [-h] -i I -o O [-s S]
myApp
optional arguments:
-h, --help show this help message and exit
-i I input
-o O output
-s S stuff
I'm not getting the config args to show. I'm not sure what I'm doing wrong here.
Thanks!
Solved it
import argparse
from argparse import RawTextHelpFormatter
parser = argparse.ArgumentParser(description='myApp',formatter_class=RawTextHelpFormatter)
parser.add_argument('-i',help='input',required=True)
parser.add_argument('-o',help='output',required=True)
parser.add_argument('-s',help='stuff',default=None,required=False)
subp = parser.add_subparsers(help='configure')
conf_parser = subp.add_parser('config')
conf_parser.add_argument('-a',help='a config file',default=None,required=False)
conf_parser.add_argument('-b',help='b config file',default=None,required=False)
args = parser.parse_args()
python sandbox/test1.py --help
usage: test1.py [-h] -i I -o O [-s S] {config} ...
myApp
positional arguments:
{config} configure
optional arguments:
-h, --help show this help message and exit
-i I input
-o O output
-s S stuff
python sandbox/test1.py config --help
usage: test1.py config [-h] [-a A] [-b B]
optional arguments:
-h, --help show this help message and exit
-a A a config file
-b B b config file
I try the following command:
subprocess.call(['sudo', 'su - postgres'], shell=True)
or
subprocess.call(['sudo', 'su', '-', 'postgres'], shell=True)
in Python2.7 (either by ipython manually writing the line, or python myfile.py being the line as part of the code), and get the sudo usage information:
usage: sudo [-D level] -h | -K | -k | -V
usage: sudo -v [-AknS] [-D level] [-g groupname|#gid] [-p prompt] [-u user
name|#uid]
usage: sudo -l[l] [-AknS] [-D level] [-g groupname|#gid] [-p prompt] [-U user
name] [-u user name|#uid] [-g groupname|#gid] [command]
usage: sudo [-AbEHknPS] [-C fd] [-D level] [-g groupname|#gid] [-p prompt] [-u
user name|#uid] [-g groupname|#gid] [VAR=value] [-i|-s] [<command>]
usage: sudo -e [-AknS] [-C fd] [-D level] [-g groupname|#gid] [-p prompt] [-u
user name|#uid] file ...
I can run the command in the shell with no problems at all. Both times it is the same shell.
Q: What am I doing wrong?
From the subprocess docs:
args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.
Therefore, your list is really a sequence. For a single command, just place the string, together, as there is no need to have it split:
subprocess.call(['sudo su - postgres'], shell=True)
I am trying to have a required mutually exclusive group with one required parameter. Below is the code which I have put
#!/usr/bin/python
import argparse
import sys
# Check for the option provided as part of arguments
def parseArgv():
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", choices=[1,2,3,4],
help = "Increase verbosity")
group.add_argument("-q", "--quiet", action="store_true", help = "Run quietly")
name = parser.add_mutually_exclusive_group(required=True)
name.add_argument("-n", "--name", help = "Name of the virtual machine")
name.add_argument("-t", "--template", help = "Name of the template to use \
for creating vm. If path is not provided then it will be looked \
under template directory.")
parser.add_argument("-s", "--save", help = "Save the machine template. If \
path is not provided then it will be saved under template directory.");
#parser.add_argument("-k", "--kick_start", required = True, help = "Name of the \
# kick start file. If path is not provided then it will be look into http \
# directory.")
if len(sys.argv) == 1:
parser.print_help()
args = parser.parse_args()
if __name__ == '__main__':
parseArgv()
Now the output of this program as follow
$ python test.py
usage: test.py [-h] [-v {1,2,3,4} | -q] (-n NAME | -t TEMPLATE) [-s SAVE]
optional arguments:
-h, --help show this help message and exit
-v {1,2,3,4}, --verbose {1,2,3,4}
Increase verbosity
-q, --quiet Run quietly
-n NAME, --name NAME Name of the virtual machine
-t TEMPLATE, --template TEMPLATE
Name of the template to use for creating vm. If path
is not provided then it will be looked under template
directory.
-s SAVE, --save SAVE Save the machine template. If path is not provided
then it will be saved under template directory.
usage: test.py [-h] [-v {1,2,3,4} | -q] (-n NAME | -t TEMPLATE) [-s SAVE]
test.py: error: one of the arguments -n/--name -t/--template is required
But if I un-comment the from line 20 - 22 then the output change as below
$ python test.py
usage: test.py [-h] [-v {1,2,3,4} | -q] (-n NAME | -t TEMPLATE) [-s SAVE] -k
KICK_START
optional arguments:
-h, --help show this help message and exit
-v {1,2,3,4}, --verbose {1,2,3,4}
Increase verbosity
-q, --quiet Run quietly
-n NAME, --name NAME Name of the virtual machine
-t TEMPLATE, --template TEMPLATE
Name of the template to use for creating vm. If path
is not provided then it will be looked under template
directory.
-s SAVE, --save SAVE Save the machine template. If path is not provided
then it will be saved under template directory.
-k KICK_START, --kick_start KICK_START
Name of the kick start file. If path is not provided
then it will be look into http directory.
usage: test.py [-h] [-v {1,2,3,4} | -q] (-n NAME | -t TEMPLATE) [-s SAVE] -k
KICK_START
test.py: error: argument -k/--kick_start is required
But I want that either -n / -t along with -k become mandatory. How to achieve the same.
You have already achieved it! Argparse only prints the first error it finds, so while it may look like it's only checking -k, it actually recuires -n/-t too. You can see this by actually giving it the -k argument.
If you provide the -k argument, the error message will change from test.py: error: argument -k/--kick_start is required to test.py: error: one of the arguments -n/--name -t/--template is required.