summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAssaf Gordon <assafgordon@gmail.com>2016-05-13 17:29:23 (GMT)
committerAssaf Gordon <assafgordon@gmail.com>2016-05-13 17:29:23 (GMT)
commit893e03e7d31d412af3d9975a91e42924b8a42618 (patch)
tree155cd484e52477a128ef3fe7cc97b395f9ff49b6
parent572a1d743a9a21ef26c19f14d058bd820e6e0f87 (diff)
downloadcode-snippets-893e03e7d31d412af3d9975a91e42924b8a42618.zip
code-snippets-893e03e7d31d412af3d9975a91e42924b8a42618.tar.gz
code-snippets-893e03e7d31d412af3d9975a91e42924b8a42618.tar.bz2
new example: argparse-more-help.py
-rwxr-xr-xargparse-more-help.py69
-rw-r--r--metadata.yml2
2 files changed, 71 insertions, 0 deletions
diff --git a/argparse-more-help.py b/argparse-more-help.py
new file mode 100755
index 0000000..de9caf7
--- /dev/null
+++ b/argparse-more-help.py
@@ -0,0 +1,69 @@
+#!/usr/bin/env python
+"""
+Example of using python's argparse module to
+offer a stand-alone option (e.g. extra help screen),
+which will skip the required parameters (e.g. the filename).
+
+Copyright (C) 2016 Assaf Gordon <assafgordon@gmail.com>
+License: MIT
+"""
+
+
+import sys,argparse
+
+class MoreHelpAction(argparse.Action):
+ def __init__(self, option_strings, dest, **kwargs):
+ super(MoreHelpAction, self).__init__(option_strings, '', nargs=0, **kwargs)
+
+ def __call__(self, parser, namespace, values, option_string=None):
+ text="""
+This is an extra help screen.
+
+Enjoy it...
+"""
+ print text
+ sys.exit(0)
+
+
+def parse_command_line():
+ # Define parameters
+ parser = argparse.ArgumentParser(
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ description="argparse example",
+ epilog="""
+
+Standard usage requires a filename,
+but using --more-help will not.
+
+Example:
+
+ # Without a filename, usage error is reported:
+ $ %(prog)s
+
+ # with a filename, program runs:
+ $ %(prog)s input.txt
+
+ # with --more-help, a differet help script is show,
+ # not requiring filename parameters
+ $ %(prog)s --more-help
+
+ """)
+
+
+ # Add special action parameter
+ parser.add_argument('--more-help', action=MoreHelpAction,
+ help="Additional information")
+
+
+
+ # Positional parameter
+ parser.add_argument('filename', metavar='FILE', help='file to process');
+ args = parser.parse_args()
+
+ return args
+
+
+if __name__ == "__main__":
+ args = parse_command_line()
+
+ print "File to process:", args.filename
diff --git a/metadata.yml b/metadata.yml
index b6eda2d..dda4eaa 100644
--- a/metadata.yml
+++ b/metadata.yml
@@ -9,6 +9,8 @@ files:
description: 'automatically duplicate stdout/err, save into a log file'
log-to-file2.sh:
description: 'automatically duplicate stdout/err, save into separate log files'
+ argparse-more-help.py:
+ description: 'implementing --more-help option'
links:
- name: posix-libc-examples
url: https://git.housegordon.org/gitweb/posix-libc-examples.git