将参数发送到Python脚本的规范方法是什么?

时间:2015-11-11 22:04:31

标签: python

文件script.py中的以下代码可以(chmod 755 script.py之后)script.py dothisscript.py dothat

import sys

def dothis():
    print "We're doing this."

def dothat():
    print "We're doing that."

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print "Error: You must specify exactly one function: dothis or dothat"
        sys.exit(1)
    if sys.argv[1] == "dothis":
        dothis()
    elif sys.argv[1] == "dothat":
        dothat()
    else:
        print "I don't know how to "+sys.argv[1]

这是从命令行调用两个函数之一的最优雅方法吗?

3 个答案:

答案 0 :(得分:3)

import argparse as ap

def dothis():
    print "We're doing this."

def dothat():
    print "We're doing that."

if __name__ == "__main__":
    parser = ap.ArgumentParser()
    parser.add_argument('thing', choices=['dothis', 'dothat'])
    args = parser.parse_args()
    f = locals()[args.thing]
    f()

答案 1 :(得分:1)

有各种选择。标准库中的argparse模块是一个。

还有一些包装使其易于使用,例如argh。这让你写:

import argh

# declaring:

def echo(text):
    "Returns given word as is."
    return text

def greet(name, greeting='Hello'):
    "Greets the user with given name. The greeting is customizable."
    return greeting + ', ' + name

# assembling:

parser = argh.ArghParser()
parser.add_commands([echo, greet])

# dispatching:

if __name__ == '__main__':
    parser.dispatch()

答案 2 :(得分:1)

我推荐argparse:https://docs.python.org/2/howto/argparse.html

它支持在其他功能之间互斥参数。