11#!/usr/bin/env python
22# coding=utf-8
33"""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.
56
67Thanks to cmd2's built-in transcript testing capability, it also serves as a test suite for argparse_example.py when
78used with the exampleSession.txt transcript.
1011argparse_example.py, verifying that the output produced matches the transcript.
1112"""
1213import argparse
14+ import sys
1315
1416from cmd2 import Cmd , make_option , options
1517
@@ -28,7 +30,7 @@ def __init__(self, ip_addr=None, port=None, transcript_files=None):
2830 Cmd .__init__ (self , use_ipython = False , transcript_files = transcript_files )
2931
3032 # 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
3234
3335 # Example of args set from the command-line (but they aren't being used here)
3436 self ._ip = ip_addr
@@ -68,8 +70,7 @@ def do_speak(self, arg, opts=None):
6870 parser .add_argument ('-i' , '--ip' , type = str , help = 'IPv4 address' )
6971
7072 # 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 ()
7374
7475 port = None
7576 if args .port :
@@ -79,12 +80,11 @@ def do_speak(self, arg, opts=None):
7980 if args .ip :
8081 ip_addr = args .ip
8182
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
8585
8686 # Instantiate your cmd2 application
87- c = CmdLineApp (transcript_files = transcripts )
87+ c = CmdLineApp ()
8888
8989 # And run your cmd2 application
9090 c .cmdloop ()
0 commit comments