File tree Expand file tree Collapse file tree 1 file changed +35
-17
lines changed
Expand file tree Collapse file tree 1 file changed +35
-17
lines changed Original file line number Diff line number Diff line change 1- import sys
1+ # encoding:utf-8
22
3- # sys.argv接收参数,第一个参数是文件名,第二个参数开始是用户输入的参数,以空格隔开
3+ # !/usr/bin/env python
44
5- def run1 ():
6- print ('I\' m action1' )
5+ # -*- Python3命令行 -*-
76
7+ import optparse
8+ import sys
89
9- def run2 ():
10- print ('I\' m action2' )
1110
11+ def process_command_line (argv ):
12+ """
13+ Return a 2-tuple: (settings object, args list).
14+ `argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
15+ """
16+ if argv is None :
17+ argv = sys .argv [1 :]
18+ # initialize the parser object:
19+ parser = optparse .OptionParser (
20+ formatter = optparse .TitledHelpFormatter (width = 78 ),
21+ add_help_option = None )
22+ # define options here:
23+ parser .add_option ( # customized description; put --help last
24+ '-h' , '--help' , action = 'help' ,
25+ help = 'Show this help message and exit.' )
26+ settings , args = parser .parse_args (argv )
27+ # check number of arguments, verify values, etc.:
28+ if args :
29+ parser .error ('program takes no command-line arguments; '
30+ '"%s" ignored.' % (args ,))
31+ # further process settings & args if necessary
32+ return settings , args
1233
13- if 2 > len ( sys . argv ):
14- print ( 'none' )
15- else :
16- action1 = sys . argv [ 1 ]
17- action2 = sys . argv [ 2 ]
34+ def main ( argv = None ):
35+ settings , args = process_command_line ( argv )
36+ # application code here, like :
37+ # run(settings, args)
38+ return 0 # success
1839
19- if 'run1' == action1 :
20- run1 ()
21- if 'run2' == action2 :
22- run2 ()
23-
24- #用法:在命令行执行脚本,python sys_argv.py run1 run2
40+ if __name__ == '__main__' :
41+ status = main ()
42+ sys .exit (status )
You can’t perform that action at this time.
0 commit comments