Tzury Bar Yochay
Tzury Bar Yochay

Reputation: 9004

Python optparse, having one option depends on another

Is there a way to get the following to work? What I am looking for, is to have a value of one option, based on the value of another.

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()

Obviously, as it is at the moment it will not work, since

local variable 'options' referenced before assignment

Upvotes: 2

Views: 2393

Answers (3)

Lennart Regebro
Lennart Regebro

Reputation: 172239

You'll have to massage the default later. If the option is the default, then do the massaging:

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)

That said, in this example, fileaction and filename seem to conflict, so that it is pointless to set both at the same time, they'll overwrite each other in ways that are not obvious. I'd let fileaction default to "cp", and add a --action-target for '/bar/baz' and then just construct the call from these pieces.

Upvotes: 0

Raphael Pr
Raphael Pr

Reputation: 954

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

Upvotes: 0

Inbar Rose
Inbar Rose

Reputation: 43447

just have them both:

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

you can use simple logic.

if options.file_name:
    #do code relating to file_action

or even

if options.file_action and not options.file_name:
    raise ValueError("No Filename specified")
# do your code here.

Upvotes: 1

Related Questions