等于签署Python的论点

use*_*915 8 python syntax arguments python-2.7

我想以下列方式从shell命令行启动python的脚本:

python script_name -temp=value1 -press=value2
Run Code Online (Sandbox Code Playgroud)

我写的是这样的:

#!/usr/bin/python

import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("temp", help="specify the temperature [K]", type=float)
parser.add_argument("press", help="specify the pressure [Pa]", type=float)

args = parser.parse_args()
temp = args.temp
press = args.press
print temp
print press
Run Code Online (Sandbox Code Playgroud)

输入可以是:

python script_name value1 value2
Run Code Online (Sandbox Code Playgroud)

如何能够以-arg = value的方式输入值?

bik*_*der 7

使用 parser.add_argument("--temp", ...)

argparser手册中有很多很好的例子:

http://docs.python.org/2.7/library/argparse.html

编辑:

对于-仅以模式-argument VALUE起作用的参数.这也适用于以...开头的参数--,但在这里您也可以使用该模式--argument=VALUE.