OptionError:optparse.py无效操作:错误

时间:2013-09-05 19:32:48

标签: python python-2.7 optparse

问候我在尝试将参数放入python脚本时收到错误。这是函数

from optparse import OptionParser

def getparams():
usage = "usage: %prog -d <dcb_ip> -p <port> "
parser = OptionParser(usage)
parser.add_option("-d", "--dcb_ip",
                  action="store",
                  dest="dcb_ip",
                  default="172.14.20.31",
                  help="Specifiy the IP address of the device, default is [%default].")
parser.add_option("-p", "--port",
                  action="store",
                  type="int",
                  dest="port",
                  default=51500,
                  help="Specify the pcl port of the monitor, default is [%default].")
parser.add_option("-i", "--interactive", action="store_true",  default=False, dest="interactive")
parser.add_option("-l", "--loop", action="store",  default=False, dest="loop")
parser.add_option("-w", "--write", action="write_mem",  default=False, dest="interactive")  #Write HART option
parser.add_option("-r", "--read", action="read_mem",  default=False, dest="interactive")
parser.add_option("-c", "--Cancel", action="cancel_mem",  default=False, dest="interactive")
(options, args) = parser.parse_args(sys.argv)    
return options

有谁知道我为什么一直

Traceback (most recent call last):
  File "C:\Users\Documents\devices_15_JUL_2013\RSimulator.py", line 73, in getparams
    parser.add_option("-w", "--write", action="write_mem",  default=False)  #Write mem option
OptionError: option -w/--write: invalid action: 'write_mem''

我认为-c可能是一种常见的选择,但即使我改变它仍然无效:(

1 个答案:

答案 0 :(得分:0)

write_memread_memcancel_mem不是action关键字的有效值;有关 的内容,请参阅Standard option actions

然而,您不希望的选项。您将目标指定为interactive,但已经用作-i--interactive选项的布尔标记。

如果您想在_mem选项中为每个选项设置布尔标记,请使用store_true操作执行此操作:

parser.add_option("-w", "--write", action="store_true", default=False, dest="write_mem")
parser.add_option("-r", "--read", action="store_true", default=False, dest="read_mem")
parser.add_option("-c", "--cancel", action="store_true", default=False, dest="cancel_mem")