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.
Related
I made a simple CLI using Typer and Pillow to change image opacity and this program only have one option: opacity.
But when I run python opacity.py --help it gives me the two typerCLI options:
Options:
--install-completion [bash|zsh|fish|powershell|pwsh]
Install completion for the specified
shell.
--show-completion [bash|zsh|fish|powershell|pwsh]
Show completion for the specified
shell, to copy it or customize the
installation.
--help Show this message and exit.
There's a way to disable it? I didn't find on docs.
I met the same problem today, i couldn't find anything except this question so dived in the source to find how Typer automatically adds this line in app, so i found this, when Typer initialiazing itself it automatically sets add_completion to True
class Typer:
def __init__(add_completion: bool = True)
So when you initialiazing your app you can add this
app = typer.Typer(add_completion=False)
This is how it looks after you add add_completion=False
Usage: main.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
As of version 0.7.0, Typer now excludes these by default if you use the typer.run() API.
Example:
# foo.py
import typer
def main():
pass
if __name__ == "__main__":
typer.run(main)
Produces:
$ pip install typer[all]==0.7.0
$ python foo.py --help
Usage: foo.py [OPTIONS]
╭─ Options ───────────────────────────────────────╮
│ --help Show this message and exit. │
╰─────────────────────────────────────────────────╯
I'm writing a separate nose2 tests.py for my program and because I want it to run on both Windows and Linux fairly seamlessly I've decided to forgo using the normal commandline nose2 and instead import it in the file and run it from there.
if __name__ == '__main__':
import nose2
nose2.main()
This works fine, no problems. But I'd like the verbose output and I can't see how to get it to do this. I've tried:
nose2.main("-v")
nose2.main(kwargs="-v")
nose2.main(args="-v")
Anyone know how to get the imported version of nose2 to run in verbose mode?
Since the PluggableTestProgram class accepts the same parameters of unittest.TestProgram, you can pass verbosity to the main function as such:
nose2.main(verbosity=2) # default is 1
See: Unittest.main documentation about verbosity
With the code
import unittest
import logging
class LoggingTest(unittest.TestCase):
def test_that_logs(self):
logging.warning("Hello")
logging.info("World")
for a in xrange(100000000000000000):
pass
I get this unexpected output:
$ nosetests --version
nosetests version 1.3.7
$ nosetests log_from_nosetest.py --nocapture --nologcapture
WARNING:root:Hello
^C
----------------------------------------------------------------------
Ran 1 test in 105.376s
OK
As can be seen. The WARNING log level message is printed, but not the INFO level one.
I've tried using the --logging-level setting but without success.
It seems a missing feature. If --nologcapture is set, nose simply ignores all logging setup, e.g. --logging-level is not used at all. You can remedy that with a
logging.basicConfig(level=logging.INFO)
in your code - not sure if that's what you want, because this kind of setup shouldn't be in library-code at all. It would be fine within the test-setup though.
This is because the default log level is warning. Set it with
logging.getLogger('').setLevel(logging.INFO)
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.
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.