2

有没有办法让以下工作?我正在寻找的是基于另一个选项的价值来获得一个选项的价值。

import optparse
parser = optparse.OptionParser()

parser.add_option("--file-name", default="/foo/bar", dest="file_name")

parser.add_option("--file-action", 
    default="cp %s /bar/baz" % (options.file_name), 
    dest="fileaction")

options, args = parser.parse_args()

显然,目前它不会起作用,因为

赋值前引用的局部变量“选项”

4

3 回答 3

1

两者都有:

parser.add_option("--file-name", dest="file_name")
parser.add_option("--file-action", dest="file_action")

你可以使用简单的逻辑。

if options.file_name:
    #do code relating to file_action

甚至

if options.file_action and not options.file_name:
    raise ValueError("No Filename specified")
# do your code here.
于 2012-12-11T13:00:03.170 回答
0

稍后您将不得不按摩默认值。如果该选项是默认选项,则进行按摩:

parser.add_option("--file-action", 
    default="cp <filename> /bar/baz", 
    dest="fileaction")

options, args = parser.parse_args()

if options.fileaction == "cp <filename> /bar/baz":
    options.fileaction = "cp %s /bar/baz" % (options.file_name)

也就是说,在这个例子中,fileaction 和 filename 似乎有冲突,因此同时设置它们是没有意义的,它们会以不明显的方式相互覆盖。我会让 fileaction 默认为"cp",并添加一个--action-targetfor '/bar/baz',然后从这些部分构建调用。

于 2012-12-11T12:58:28.997 回答
0

Your parser is a handler. It will explain python what you will do with the command line recieved when the programme is launch. Therefore, it is incorrect to have a dependance in your options.

What I advise you, is to deal with the default behaviour in your code. You can do something like :

parser.add_option("--file-action", 
default=None, 
dest="fileaction")

options, args = parser.parse_args()

# Manage the default behaviour
if not options.fileaction:
    fileaction = "cp %s /bar/baz" % (options.file_name)
    # You could then use fileaction the way you would use options.fileaction
于 2012-12-11T13:06:30.503 回答