1
1
#!/usr/bin/env python
2
2
# coding=utf-8
3
3
"""A sample application for cmd2 showing how to use Argparse to process command line arguments for your application.
4
- It doubles as an example of how you can still do transcript testing even if allow_cli_args is false.
4
+ It parses command line arguments looking for known arguments, but then still passes any unknown arguments onto cmd2
5
+ to treat them as arguments at invocation.
5
6
6
7
Thanks to cmd2's built-in transcript testing capability, it also serves as a test suite for argparse_example.py when
7
8
used with the exampleSession.txt transcript.
10
11
argparse_example.py, verifying that the output produced matches the transcript.
11
12
"""
12
13
import argparse
14
+ import sys
13
15
14
16
from cmd2 import Cmd , make_option , options
15
17
@@ -28,7 +30,7 @@ def __init__(self, ip_addr=None, port=None, transcript_files=None):
28
30
Cmd .__init__ (self , use_ipython = False , transcript_files = transcript_files )
29
31
30
32
# Disable cmd's usage of command-line arguments as commands to be run at invocation
31
- self .allow_cli_args = False
33
+ # self.allow_cli_args = False
32
34
33
35
# Example of args set from the command-line (but they aren't being used here)
34
36
self ._ip = ip_addr
@@ -68,8 +70,7 @@ def do_speak(self, arg, opts=None):
68
70
parser .add_argument ('-i' , '--ip' , type = str , help = 'IPv4 address' )
69
71
70
72
# Add an argument which enables transcript testing
71
- parser .add_argument ('-t' , '--test' , type = str , help = 'Test against transcript in FILE (wildcards OK)' )
72
- args = parser .parse_args ()
73
+ args , unknown_args = parser .parse_known_args ()
73
74
74
75
port = None
75
76
if args .port :
@@ -79,12 +80,11 @@ def do_speak(self, arg, opts=None):
79
80
if args .ip :
80
81
ip_addr = args .ip
81
82
82
- transcripts = None
83
- if args .test :
84
- transcripts = [args .test ]
83
+ # Perform surgery on sys.argv to remove the arguments which have already been processed by argparse
84
+ sys .argv = sys .argv [:1 ] + unknown_args
85
85
86
86
# Instantiate your cmd2 application
87
- c = CmdLineApp (transcript_files = transcripts )
87
+ c = CmdLineApp ()
88
88
89
89
# And run your cmd2 application
90
90
c .cmdloop ()
0 commit comments