[Tutor] checking input parameters
Peter Otten
__peter__ at web.de
Fri Aug 31 10:58:36 CEST 2012
Bala subramanian wrote:
> I use the following way to check for the input parameters. I would
> like to know if there is a any better way to show or describe the
> script usage. So when the user just runs it without any input params.,
> the program shd not execute but just shows the documentation.
>
> from sys import argv
> if not argv[1:]:
> print 'Program usage: python script file-list1 file-list2'
> print 'file list should contain the names of the atom list'
> --------
> --------
I may look like a lot of overhead at first, but in the long run it will pay
off if you use argparse:
$ cat argparse_demo.py
def main():
import argparse
parser = argparse.ArgumentParser(
description="what the script is supposed to do")
parser.add_argument(
"file_list1", metavar="file-list1",
help="your help text for file-list1")
parser.add_argument(
"file_list2", metavar="file-list2",
help="your help text for file-list2")
args = parser.parse_args()
print "Do something with {!r} and {!r}".format(
args.file_list1, args.file_list2)
if __name__ == "__main__":
main()
$ python argparse_demo.py
usage: argparse_demo.py [-h] file-list1 file-list2
argparse_demo.py: error: too few arguments
$ python argparse_demo.py -h
usage: argparse_demo.py [-h] file-list1 file-list2
what the script is supposed to do
positional arguments:
file-list1 your help text for file-list1
file-list2 your help text for file-list2
optional arguments:
-h, --help show this help message and exit
$ python argparse_demo.py alpha.txt beta.txt
Do something with 'alpha.txt' and 'beta.txt'
For more see the documentation at
http://docs.python.org/howto/argparse.html#id1
More information about the Tutor
mailing list