pyinstaller is not compatible with python argparse -h - python

In the python script, ArgumentParser will displays the parser’s help message by default if -h or --help is supplied at the command line.
(base) D:\Study\Github\BVPA-GUI>python src\plot_auto.py -h
usage: plot_auto.py [-h] [--legend] [--figname FIGNAME]
optional arguments:
-h, --help show this help message and exit
--legend Show legend on plot.
--figname FIGNAME Specify the window title.
However it will not work if I compile the python script into exe application by pyinstaller.
D:\Study\Github\BVPA-GUI>.\bin\plotting\plot_auto.exe -h
What is the reason for this and what can I do about this?

Have you ever used sys.argv with pyinstaller?
You can check that it works well.
See argparse python official document, especially parse_args parts.
It makes a parsed arguments with the given console arguments or the given string list on function interface, parse_args(['arg1', 'arg2', ... ]).
Let's apply to your application. Very simple.
import sys, argparse
parser = argparse.ArgumentParser()
# add arguments settings ------------
.
.
.
#------------------------------------
if __name__ == "__main__":
args = parser.parse_args(sys.argv[1:])
# Your program code
I also tried same work with you.
It worked well to me.
I hope it is usefull to you too.
#Note:
In the official document said that parse_args function get default arguments from sys.argv but it doesn't seems to work with pyinstaller.
The above is just manually add such progress.

Related

How to program a python file to use terminal options on mac

I am building a python file and instead of asking for user input I want it to get the information on the execution command. For example, I want to be able to type in
python code.py -i "information"
Instead of having to execute code.py and then tell the code "information". How do I do this? P.S. I am using MacOS mojave as the tags indicate. Thanks.
You can utilize sys.argv in your Python script to read command-line arguments and store them in a list of strings that you can then parse, as follows:
from __future__ import print_function
import sys
print(sys.argv)
Then, from the terminal:
> python code.py -i "foo bar"
['code.py', '-i', 'foo bar']
You can use python's argparse module to use command line arguments.
https://docs.python.org/3/library/argparse.html

python : arg_parser argument add alias

I'm trying to have some specific printing with python argument parsing, but there is something i don't manage to do.
parser.add_argument('-m' , help="test a specific module")
Above is my code.
optional arguments:
-h, --help show this help message and exit
-m M test a specific module
Above is the result.
But what i want to have is :
optional arguments:
-h, --help show this help message and exit
-m MODULE test a specific module
I know it's not really important but i would really like to have this output.
Thanks !
This could be solved by adding metavar
parser.add_argument('-m', metavar='MODULE', help="test a specific module")

Modify Usage string on Click command line interface on Windows

I have a Python package called tdsmthat I have converted for the first time to a command-line interface using Armin Ronacher's Click package. I have set my scripts up within this directory structure:
Also I have created a setup.py file:
from setuptools import setup
setup(
name='tdsm',
version='0.1',
py_modules=['tdsm.scripts.data_manager',
'tdsm.scripts.visuals'],
include_package_data=True,
install_requires=[
'click',
'numpy',
'scipy',
'pandas',
'wand',
'matplotlib',
],
entry_points='''
[console_scripts]
tdsm=tdsm.main:cli
''',
)
After a pip install --editable ., I get it working, up to a point:
# tdsm --help
Now emits:
Usage: tdsm-script.py [OPTIONS] COMMAND [ARGS]...
TDSM standard workflow -- typical sequence of commands:
`init <path>` or `open <path>`: to set up the project or to open
a new session on an existing project.
`plot`: framework for setting up plots, display layers, and styling.
Options:
--help Show this message and exit.
Commands:
init Set up a project from scratch.
plot Initialize a plotting session.
Note the usage statement says Usage: tdsm-script.py [OPTIONS] COMMAND [ARGS]... and not Usage: tdsm [OPTIONS] COMMAND [ARGS]... as I believe it should. Since I am expecting this to be used by non-programmers, I don't want users delving through the system looking for a non-existent file...
Poring through the docs I can see how to change every aspect of the help text but not this initial reference to tdsm-script.py. Any pointers on what I am doing wrong?
The issue was resolved in the GitHub bug discussion thread by Markus Unterwaditzer. I reproduce it here for the record.
One just calls the command (or group, in my case) with an explicit prog_name argument, thus:
import click
#click.group()
def cli():
pass
#cli.command(short_help='Set up a project from scratch.')
def init():
pass
#cli.command(short_help='Initialise a plotting session.')
def plot():
pass
cli(prog_name='tdsm') # Call with explicit `prog_name`
On installing the package, the right Usage is reported:
# tdsm --help
Usage: tdsm [OPTIONS] COMMAND [ARGS]...
You're not the only one with this problem. Judging from your screenshot it looks like you're on Windows, and it's an open bug with Click.
The problem is that Click appears to be autodetecting the program's name from argv[0]. See the code in core.py that does this.
The bug report link above suggests some hackish ways of getting around this, including monkey-patching. Unfortunately the last comment on the bug is from July 28 -- perhaps mention on that thread that you're also having this issue. Good luck.

Execute python script with a variable from linux shell

This might be an easy question but I don't know the name of what I'm trying to do, so I don't know how to search for it.
Basically when I'm in terminal (linux command line) and I type
$ python do_something.py stuff
I want to get the stuff to mean something for my script. So two questions:
How is this called?
How can I do it?
The simplest way is for the do_something.py script to import sys and access the "stuff" command-line argument as sys.argv(1). There are many fancier ways, of course.
What you're asking for is called argument parsing.
To do this the proper way, you should definitively use argparse.
It's a neat and yet very powerful library to make argument parsing more efficient. Plus, it makes your scripts manage arguments the proper Linux way, by default.
Basic example:
import argparse
parser = argparse.ArgumentParser(description='My argparse program')
parser.add_argument('--verbose',
action='store_true',
help='sets output to verbose' )
args = parser.parse_args()
if args.verbose:
print("~ Verbose!")
else:
print("~ Not so verbose")
Then you can do cool stuff like:
$ python3 myscript.py --verbose
~ Verbose!
And what's even cooler, it provides an automatic --help (or -h) argument:
$ python3 myscript.py --help
usage: myscript.py [-h] [--verbose]
My argparse program
optional arguments:
-h, --help show this help message and exit
--verbose sets output to verbose
This is the kind of library that allows you to quite easily do complicated stuff like:
./myscript.py --password=no -c -o --keep_moving --name="Robert"
Here is a link to a nice tutorial from which the above example has been freely adapted.

How can I customize python unitest.py --help?

I know this is possible, I'm a newbie on Python. Looked at nose. But nose is not what we require. There should be some way to customize when I run python unittest.py --help on my own. Can any python people throw some light on this on how or where we can change. I'm using python 2.6.6
Alright, you're looking at customizing unittest.TestProgram. You'll want to create something like myunittest.py and in that module you'll do something like:
# myunittest.py
from unittest import TestProgram
class MyTestProgram(TestProgram):
USAGE = """\
Usage: %(progName)s [options] [test] [...]
Options:
-h, --help Show this message
-v, --verbose Verbose output
-q, --quiet Minimal output
Examples:
%(progName)s - run default set of tests
%(progName)s MyTestSuite - run suite 'MyTestSuite'
%(progName)s MyTestCase.testSomething - run MyTestCase.testSomething
%(progName)s MyTestCase - run all 'test*' test methods
in MyTestCase
"""
# additional changes here...
main = MyTestProgram
if __name__ == "__main__":
main(module=None)
Just changing USAGE may be all you really care about as that's the text printed by python unittest.py --help but you could obviously customize more.
Note this is specific to Python2.6. Python 2.7+ uses unittest2 which I'm not really familiar with at this point.

Categories

Resources