Execute python script with a variable from linux shell - python

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.

Related

pyinstaller is not compatible with python argparse -h

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.

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")

call python module functions from command line

I would like to know if there is a way to call module functions from the command line. My problem is that I have a file package called find_mutations. This requires that the input files are sorted in a specific way, so i made a function to do so. I would like the user to be able to have the option to run the code normally:
$ python -m find_mutations -h
or run the specific sort_files function:
$ python -m find_mutations.sort_files -h
Is something like this possible? If so, does the sort_files function need to be in its own strip? Do I need to add something to my __init__.py script? The package install properly and runs fine, I would just like to add this.
You could add flags to run the function. The following example is not a good way to work with command arguments, but demonstrates the idea.
import sys
if __name__ == "__main__":
if '-s' in sys.argv:
sort_files()
Add a flag to run the specific function, in this case -s to sort the files.

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