summaryrefslogtreecommitdiff
path: root/examples/argparse_example.py
diff options
context:
space:
mode:
authorJared Crapo <jared@kotfu.net>2017-12-11 19:15:15 -0700
committerJared Crapo <jared@kotfu.net>2017-12-11 19:15:15 -0700
commit67e669e3345fb637e4f4779691a7a8ec4b1763f6 (patch)
tree7632e68cc845e1089111e9f10b105bce8c6d5a46 /examples/argparse_example.py
parent4f57dc14a7ffc2cbd741622da7d05d42ba7f7789 (diff)
parent63b0c6b3a92cab837a71bbad78e777c522823c93 (diff)
downloadcmd2-git-67e669e3345fb637e4f4779691a7a8ec4b1763f6.tar.gz
Merge branch 'master' of https://github.com/python-cmd2/cmd2 into argparse
Diffstat (limited to 'examples/argparse_example.py')
-rwxr-xr-xexamples/argparse_example.py16
1 files changed, 8 insertions, 8 deletions
diff --git a/examples/argparse_example.py b/examples/argparse_example.py
index 8c25b0ef..805bab77 100755
--- a/examples/argparse_example.py
+++ b/examples/argparse_example.py
@@ -1,7 +1,8 @@
#!/usr/bin/env python
# coding=utf-8
"""A sample application for cmd2 showing how to use Argparse to process command line arguments for your application.
-It doubles as an example of how you can still do transcript testing even if allow_cli_args is false.
+It parses command line arguments looking for known arguments, but then still passes any unknown arguments onto cmd2
+to treat them as arguments at invocation.
Thanks to cmd2's built-in transcript testing capability, it also serves as a test suite for argparse_example.py when
used with the exampleSession.txt transcript.
@@ -10,6 +11,7 @@ Running `python argparse_example.py -t exampleSession.txt` will run all the comm
argparse_example.py, verifying that the output produced matches the transcript.
"""
import argparse
+import sys
from cmd2 import Cmd, make_option, options, with_argument_parser
@@ -28,7 +30,7 @@ class CmdLineApp(Cmd):
Cmd.__init__(self, use_ipython=False, transcript_files=transcript_files)
# Disable cmd's usage of command-line arguments as commands to be run at invocation
- self.allow_cli_args = False
+ # self.allow_cli_args = False
# Example of args set from the command-line (but they aren't being used here)
self._ip = ip_addr
@@ -92,8 +94,7 @@ if __name__ == '__main__':
parser.add_argument('-i', '--ip', type=str, help='IPv4 address')
# Add an argument which enables transcript testing
- parser.add_argument('-t', '--test', type=str, help='Test against transcript in FILE (wildcards OK)')
- args = parser.parse_args()
+ args, unknown_args = parser.parse_known_args()
port = None
if args.port:
@@ -103,12 +104,11 @@ if __name__ == '__main__':
if args.ip:
ip_addr = args.ip
- transcripts = None
- if args.test:
- transcripts = [args.test]
+ # Perform surgery on sys.argv to remove the arguments which have already been processed by argparse
+ sys.argv = sys.argv[:1] + unknown_args
# Instantiate your cmd2 application
- c = CmdLineApp(transcript_files=transcripts)
+ c = CmdLineApp()
# And run your cmd2 application
c.cmdloop()