a6a0a07cb0
Signed-off-by: David Rotermund <54365609+davrot@users.noreply.github.com> |
||
---|---|---|
.. | ||
README.md |
Argh
{:.no_toc}
* TOC {:toc}The goal
Argh helps to handle command line arguments in a big way. Don't use the build-in Python stuff for that.
Questions to David Rotermund
pip install argh
Simple example
No argument is required
The arguments are now only optional for the function call:
import argh
def main(first_parameter: int = 1, second_parameter: int = 2, third_parameter: bool = True) -> None:
print("Main")
if __name__ == "__main__":
argh.dispatch_command(main)
python test.py
Output
Main
python test.py --help
Output
usage: test.py [-h] [-f FIRST_PARAMETER] [-s SECOND_PARAMETER] [-t]
options:
-h, --help show this help message and exit
-f FIRST_PARAMETER, --first-parameter FIRST_PARAMETER
1
-s SECOND_PARAMETER, --second-parameter SECOND_PARAMETER
2
-t, --third-parameter
True
Note: For boolean parameters using the option switches them to the other state. Here python test.py sets third-parameter=True and python test.py -t sets third-parameter=False.
One argument is required
import argh
def main(first_parameter: int, second_parameter: int = 2, third_parameter: bool = True) -> None:
print("Main")
if __name__ == "__main__":
argh.dispatch_command(main)
python test.py
Output
usage: test.py [-h] [-s SECOND_PARAMETER] [-t] first-parameter
test.py: error: the following arguments are required: first-parameter
python test.py 1
Output
Main
More than one function
Sometimes we have a collection of function. This is how we select one of those:
import argh
def main_1(
first_parameter: int = 1, second_parameter: int = 2, third_parameter: bool = True
) -> None:
print("Main 1")
def main_2(first_parameter: int = 1) -> None:
print("Main 2")
if __name__ == "__main__":
parser = argh.ArghParser()
parser.add_commands([main_1, main_2])
parser.dispatch()
python test.py
Output
usage: test.py [-h] {main-1,main-2} ...
python test.py main-1
python test.py main-2
Output:
Main 1
Main 2
python test.py main-1 --help
python test.py main-2 --help
Output:
usage: test.py main-1 [-h] [-f FIRST_PARAMETER] [-s SECOND_PARAMETER] [-t]
options:
-h, --help show this help message and exit
-f FIRST_PARAMETER, --first-parameter FIRST_PARAMETER
1
-s SECOND_PARAMETER, --second-parameter SECOND_PARAMETER
2
-t, --third-parameter
True
usage: test.py main-2 [-h] [-f FIRST_PARAMETER]
options:
-h, --help show this help message and exit
-f FIRST_PARAMETER, --first-parameter FIRST_PARAMETER
1
Reference
** Argh