BuZz
BuZz

Reputation: 17495

python : use optparse on given list rather than on system command line arguments

within the frame of a python application, I need to make calls to several of my scripts that were largely using optparse. They all have an entry point of this form :

if __name__ == '__main__':
    mains(sys.argv)

I just called my main function mains thinking that my problem initially came from there. Then, the mains always start like that, as an example :

def mains( argv ):
    parser = OptionParser()
    parser.add_option("-f", "--file", dest="filename", help="write result to FILE", metavar="FILE")
    parser.add_option("-x", "--filter", dest="filterset", help="filters", metavar="FILTERS")
    parser.add_option("-n", "--nameonly", dest="nameonly", help="nameonly", metavar="NAME_ONLY")
    parser.add_option("-z", "--ignorezeros", dest="ignorezeros", help="ignorezeros", metavar="IGNORE_ZEROS")
    parser.add_option("-y", "--xfilter", dest="xfilter", help="xfilter", metavar="X_FILTERS")

The argv here isn't used by optparser, I do not find how to pass it to it. From my actual principal script, I thought I could call these mains by just passing the arguments as a list. Obvioulsy, in the current state the sub scripts will always pick up the command line... How to pass the arguments myself instead ?

UPDATE : my script trying to make those calls to subcripts is called this way from the console :

start.py -df

The problem : optparse from the first subscript tells me that "d" is not a valid option, which shows it is picking the console arguments at the moment.

Upvotes: 1

Views: 454

Answers (4)

kindall
kindall

Reputation: 184405

Although others have answered your immediate question, I would strongly recommend putting all your argument-parsing stuff in the if __name__ == "__main__" section of your script rather than in the main() function. Your main() function should behave more like a normal Python function. That way, if you need to call it from another module, you don't have to fake up an argv and pretend you're calling it from the command line.

Upvotes: 2

Dan D.
Dan D.

Reputation: 74675

this is the answer from http://docs.python.org/library/optparse.html

(If you like, you can pass a custom argument list to parse_args(), but that’s rarely necessary: by default it uses sys.argv[1:].)

instead of:

(options, args) = parser.parse_args()

do:

(options, args) = parser.parse_args(argv)

possible chop off the first item if it is the program name

Upvotes: 1

David K. Hess
David K. Hess

Reputation: 17246

You left out the call to parse your options:

parser.parse_args(argv)

parse_args takes an optional argument which will be used for parsing rather than sys.argv.

Upvotes: 3

Johannes Charra
Johannes Charra

Reputation: 29953

You're passing the argument list as a single argument, you have to define mains as

def mains(*args):
    ...

instead and call it via

mains(*sys.argv)

Upvotes: 1

Related Questions