• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

python 带可选参数的命令行执行

python 水墨上仙 2573次浏览

很多命令行软件都带有可选参数,这段代码可以用来读取各种命令行参数

#!/usr/bin/env python
#
# [代码名字: Show optparse]
# [代码分类: Python Core]
# [代码描述: GNU style arguments via optparse]
# [代码作者: Jurjen Stellingwerff <jurjen@stwerff.xs4all.nl>]
# [代码协议: GPL]
# example show_optparse.py
import optparse, sys
program = "show_optparse.py"
# usefull when the program alters from the normal python file
version = """%prog 0.1
Copyright (C) 2010 Jurjen Stellingwerff
Lisense GPL: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRENTY, to the extent permittable by law.
Written by Jurjen Stellingwerff.
"""
usage = "Usage: %prog [OPTION]... [REST]"
description = "Demonstrates python code for GNU style arguments."
def do_single(option, opt, value, parser):
    print value
parser = optparse.OptionParser(usage=usage, version=version, description=description, prog=program)
parser.add_option("-?", action="help", help=optparse.SUPPRESS_HELP)
parser.add_option("-f", "--file", dest="filename", action="append",
                  help="display this file", metavar="FILE")
parser.add_option("-q", "--quiet",
                  action="store_false", dest="verbose", default=True,
                  help="don't print status messages to stdout")
parser.add_option("--this-is-a-bit-too-long-argument", metavar="SOMETHING",
                  help="when arguments get too long the line splits, this also works for the longer help strings")
parser.add_option("-s", metavar="SOMETHING", action="callback", callback=do_single, type="string",
                  help="single token argument with a parameter")
group = optparse.OptionGroup(parser, "\nReport arguments bugs to jurjen@stwerff.xs4all.nl\nPython-snippets homepage: <https://code.launchpad.net/python-snippets>")
parser.add_option_group(group)
(options, args) = parser.parse_args()
if options.this_is_a_bit_too_long_argument:
    print options.this_is_a_bit_too_long_argument
if options.filename:
    for filename in options.filename:
        if options.verbose:
            print "Printing file",filename
        try:
            f = open(filename)
            for line in f.readlines():
                print line.rstrip()
        except IOError:
            print "No such file: "+options.filename
for rest in args:
    print "Rest:",rest
# demonstrate the help page when there are no parameters given
# not very useful in an actual program
if len(sys.argv)==1:
    parser.print_help()

 


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明python 带可选参数的命令行执行
喜欢 (0)
加载中……