Python中 命令行参数传递 与 处理

英文原文: http://www.artima.com/weblogs/viewpost.jsp?thread=4829

   很多人会在  if __name__ == "__main__":  中写N多行的代码。 一般情况这是没问题的。 但如果你需要以命令行的方式运行调试, 那么就不方便了。

 

   而这个文章中像C一样定义了一个main()函数, 在  if __name__ == "__main__": 中只有一行 main() 调用, 很好的代码结构!

  而且还有一个好处:你可以通过修改main()的调用参数,达到随意修改命令行参数的目的。

 

First, we change main() to take an optional 'argv' argument, which allows us to call it from the interactive Python prompt:

def main(argv=None):
    if argv is None:
        argv = sys.argv
    # etc., replacing sys.argv with argv in the getopt() call.
 首先, 让main()接受默认参数, 然后在main()里头判断, 如果没有给main参数的话,就是用sys.argv作为参数。
 

Note that we fill in the default for argv dynamically. This is more flexible than writing

def main(argv=sys.argv):
    # etc.

because sys.argv might have been changed by the time the call is made; the default argument is calculated at the time the main() function is defined, for all times.

  而这种方法更灵活! 因为在main()内部引用 sys.argv参数时, sys.argv参数可能在调用main()前被我们自己的代码修改过了。 而main(argv=sys.argv)的定义方式, 保证了传给main()的默认参数一定是执行该脚本文件时给的参数!!! 因为Python函数的默认参数是在'编译'阶段就确定了,在运行过程中是不会被修改的。

 

 

 ====== 下面与译文无关, 只是一个练习: =====

下面是从 http://blog.sina.com.cn/s/blog_71c19c620100r7mk.html   上摘抄的:

使用getopt模块处理Unix模式的命令行选项:

getopt模块用于抽出命令行选项和参数,也就是sys.argv。命令行选项使得程序的参数更加灵活。支持短选项模式和长选项模式。
    # scriptname.py

    import getopt

    shortargs = 'f:t'
    longargs = ['directory-prefix=', 'format', '--f_long=']
    opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )


getopt函数的格式是getopt.getopt ( [命令行参数列表], "短选项", [长选项列表] )
短选项名后的冒号(:)表示该选项必须有附加的参数。                    
长选项名后的等号(=)表示该选项必须有附加的参数。
返回opts和args。
opts是一个参数选项及其value的元组( ( '-f', 'hello'), ( '-t', '' ), ( '--format', '' ), ( '--directory-prefix', '/home' ) )
args是一个除去有用参数外其他的命令行输入 ( 'a', 'b' )

然后遍历opts便可以获取所有的命令行选项及其对应参数了。
    for opt, val in opts:
        if opt in ( '-f', '--f_long' ):
            pass

 

对上边的片段, 我整理了一个例子:bell@bell-desktop:/tmp$ cat py_optParse.py
import sys
import getopt

shortargs = 'f:t'
longargs = ['directory-prefix=', 'format', '--f_long=']                        

 # 这时要求长选项参数名字为: ----f_long

 #如果执行python py_optParse.py --f_long  a.txt   那么出错: option --f_long not recognized

 

opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )

print "opts:", opts
print "args:", args

class Usage(Exception):
   def __init__(self, msg):
     self.msg = msg

 

parameter_missing = True

for opt, val in opts:
    #if opt in ( '-f', '--f_long' ):
    if opt in ( '-f', '----f_long' ):
        parameter_missing = False

if(parameter_missing):
   raise Usage("missing argument!")


bell@bell-desktop:/tmp$ python py_optParse.py -f a.txt
opts: [('-f', 'a.txt')]
args: []
bell@bell-desktop:/tmp$ python py_optParse.py --f_long a.txt
Traceback (most recent call last):
  File "py_optParse.py", line 6, in <module>
    opts, args = getopt.getopt( sys.argv[1:], shortargs, longargs )
  File "/usr/lib/python2.6/getopt.py", line 89, in getopt
    opts, args = do_longs(opts, args[0][2:], longopts, args[1:])
  File "/usr/lib/python2.6/getopt.py", line 153, in do_longs
    has_arg, opt = long_has_args(opt, longopts)
  File "/usr/lib/python2.6/getopt.py", line 170, in long_has_args
    raise GetoptError('option --%s not recognized' % opt, opt)
getopt.GetoptError: option --f_long not recognized
bell@bell-desktop:/tmp$ python py_optParse.py ----f_long a.txt
opts: [('----f_long', 'a.txt')]
args: []
Traceback (most recent call last):
  File "py_optParse.py", line 24, in <module>
    raise Usage("missing argument!")
__main__.Usage
bell@bell-desktop:/tmp$

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值