How do you add options in python?
I have a Python script a.py and b.py, I'd like to call the main function of b.py and pass arguments from a.py. How to add option in a.py from inside the code and pass it to the main of b.py ?. I tried adding the dictionary my additional option but for some unknown reason the b.py doesn't get the right value. The add_option only works for command line option. Show
I've imported b inside a.py, I'm trying to pass readOnly value to main in b.py. Basically I don't want to pass readOnly from a.py as command line but pass the readOnly through the code inside a.py.
Why this code doesn't work ?. TIA, John Source code: Lib/optparse.py Deprecated since version 3.2: The
Here’s an example
of using from optparse import OptionParser ... parser = OptionParser() parser.add_option("-f", "--file", dest="filename", help="write report to FILE", metavar="FILE") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", default=True, help="don't print status messages to stdout") (options, args) = parser.parse_args() With these few lines of code, users of your script can now do the “usual thing” on the command-line, for example: <yourscript> --file=outfile -q As it parses the command line, <yourscript> -f outfile --quiet <yourscript> --quiet --file outfile <yourscript> -q -foutfile <yourscript> -qfoutfile Additionally, users can run one of the following <yourscript> -h <yourscript> --help and Usage: where the value of yourscript is determined at runtime (normally from Background¶
Terminology¶argumenta string entered on the command-line, and passed by the shell to It is occasionally desirable
to substitute an argument list other than an argument used to supply extra information to guide or customize the execution of a program. There are many different syntaxes for options; the traditional Unix syntax is a hyphen (“-”) followed by a single letter, e.g. Some other option syntaxes that the world has seen include:
These option syntaxes are not supported by an argument
that follows an option, is closely associated with that option, and is consumed from the argument list when that option is. With or included in the same argument: Typically, a given option either takes an argument or it doesn’t. Lots of people
want an “optional option arguments” feature, meaning that some options will take an argument if they see it, and won’t if they don’t. This is somewhat controversial, because it makes parsing ambiguous: if something leftover in the argument list after options have been parsed, i.e. after options and their arguments have been parsed and removed from the argument list. required optionan option that must be
supplied on the command-line; note that the phrase “required option” is self-contradictory in English. For example, consider this hypothetical command-line: prog -v --report report.txt foo bar
What are options for?¶Options are used to provide extra information to tune or customize the execution of a program. In case it
wasn’t clear, options are usually optional. A program should be able to run just fine with no options whatsoever. (Pick a random program from the Unix or GNU toolsets. Can it run without any options at all and still make sense? The main exceptions are Lots of people want their programs to have “required options”. Think about it. If it’s required, then it’s not optional! If there is a piece of information that your program absolutely requires in order to run successfully, that’s what positional arguments are for. As an example of good command-line interface design, consider the humble cp SOURCE DEST cp SOURCE ... DEST-DIR You can get pretty far with just that. Most What are positional arguments for?¶Positional arguments are for those pieces of information that your program absolutely, positively requires to run. A good user interface should have as few absolute requirements as possible. If your program requires 17 distinct pieces of information in order to run successfully, it doesn’t much matter how you get that information from the user—most people will give up and walk away before they successfully run the program. This applies whether the user interface is a command-line, a configuration file, or a GUI: if you make that many demands on your users, most of them will simply give up. In short, try to minimize the amount of information that users are absolutely required to supply—use sensible defaults whenever possible. Of course, you also want to make your programs reasonably flexible. That’s what options are for. Again, it doesn’t matter if they are entries in a config file, widgets in the “Preferences” dialog of a GUI, or command-line options—the more options you implement, the more flexible your program is, and the more complicated its implementation becomes. Too much flexibility has drawbacks as well, of course; too many options can overwhelm users and make your code much harder to maintain. Tutorial¶While First, you need to import the OptionParser class; then, early in the main program, create an OptionParser instance: from optparse import OptionParser ... parser = OptionParser() Then you can start defining options. The basic syntax is: parser.add_option(opt_str, ..., attr=value, ...) Each option has one or more option strings, such as Typically, each option will have one short option string and one long option string, e.g.: parser.add_option("-f", "--file", ...) You’re free to define as many short option strings and as many long option strings as you like (including zero), as long as there is at least one option string overall. The option strings passed to Once all of your options are defined, instruct
(options, args) = parser.parse_args() (If you like, you can pass a custom argument list to
This tutorial section only covers the four most important option attributes: Understanding option actions¶Actions tell
If you don’t specify an option
action, The store action¶The most common option action is For example: parser.add_option("-f", "--file", action="store", type="string", dest="filename") Now let’s make up a fake command line and ask args = ["-f", "foo.txt"] (options, args) = parser.parse_args(args) When Some other option types supported by
parser.add_option("-n", type="int", dest="num") Note that this option has no long option string, which is perfectly acceptable. Also, there’s no explicit action, since the default is Let’s parse another fake command-line. This time, we’ll jam the option
argument right up against the option: since (options, args) = parser.parse_args(["-n42"]) print(options.num) will print If you don’t specify a type, parser.add_option("-f", "--file", dest="filename") If you don’t supply a destination,
Handling boolean (flag) options¶Flag options—set a variable to true or false
when a particular option is seen—are quite common. parser.add_option("-v", action="store_true", dest="verbose") parser.add_option("-q", action="store_false", dest="verbose") Here we have two different options with the same destination, which is perfectly OK. (It just means you have to be a bit careful when setting default values—see below.) When Other actions¶Some other actions supported by "store_const" store a constant value "append" append this option’s argument to a list "count"
increment a counter by one "callback" call a specified function These are covered in section Reference Guide, and section Option Callbacks. Default values¶All of the above examples involve setting some variable (the “destination”) when certain command-line options are seen. What happens if those options are never seen? Since we didn’t supply any defaults, they are all set to First, consider the verbose/quiet example. If we want
parser.add_option("-v", action="store_true", dest="verbose", default=True) parser.add_option("-q", action="store_false", dest="verbose") Since default values apply to the destination rather than to any particular option, and these two options happen to have the same destination, this is exactly equivalent: parser.add_option("-v", action="store_true", dest="verbose") parser.add_option("-q", action="store_false", dest="verbose", default=True) Consider this: parser.add_option("-v", action="store_true", dest="verbose", default=False) parser.add_option("-q", action="store_false", dest="verbose", default=True) Again, the default value for A clearer way to specify default values is the parser.set_defaults(verbose=True) parser.add_option(...) (options, args) = parser.parse_args() As before, the last value specified for a given option destination is the one that counts. For clarity, try to use one method or the other of setting default values, not both. Generating help¶
usage = "usage: %prog [options] arg1 arg2" parser = OptionParser(usage=usage) parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=True, help="make lots of noise [default]") parser.add_option("-q", "--quiet", action="store_false", dest="verbose", help="be vewwy quiet (I'm hunting wabbits)") parser.add_option("-f", "--filename", metavar="FILE", help="write output to FILE") parser.add_option("-m", "--mode", default="intermediate", help="interaction mode: novice, intermediate, " "or expert [default: %default]") If
Usage: (If the help output is triggered by a help option, There’s a lot going on here to help
Grouping Options¶When dealing with many options, it is convenient to group these options for better help output. An An option group is obtained using the
class optparse. OptionGroup (parser, title,
description=None)¶where
Once all the options are declared, using the
Continuing with the parser defined in the previous section, adding an group = OptionGroup(parser, "Dangerous Options", "Caution: use these options at your own risk. " "It is believed that some of them bite.") group.add_option("-g", action="store_true", help="Group option.") parser.add_option_group(group) This would result in the following help output: Usage: A bit more complete example might involve using more than one group: still extending the previous example: group = OptionGroup(parser, "Dangerous Options", "Caution: use these options at your own risk. " "It is believed that some of them bite.") group.add_option("-g", action="store_true", help="Group option.") parser.add_option_group(group) group = OptionGroup(parser, "Debug Options") group.add_option("-d", "--debug", action="store_true", help="Print debug information") group.add_option("-s", "--sql", action="store_true", help="Print all SQL statements executed") group.add_option("-e", action="store_true", help="Print every action done") parser.add_option_group(group) that results in the following output: Usage: Another interesting method, in particular when working programmatically with option groups is: OptionParser. get_option_group (opt_str)¶Return the Printing a version string¶Similar
to the brief usage string, parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
For example, if your script is called $ /usr/bin/foo --version foo 1.0 The following two methods can be used to print and get the
OptionParser. print_version (file=None)¶Print the version message for the current program ( OptionParser. get_version ()¶Same as How optparse handles errors¶There are two broad classes of errors that
Handling user errors is much more important, since they are guaranteed to happen no matter how stable your code is.
(options, args) = parser.parse_args() ... if options.a and options.b: parser.error("options -a and -b are mutually exclusive") In either case, Consider the first example above, where the user passes $ /usr/bin/foo -n 4x Usage: foo [options] foo: error: option -n: invalid integer value: '4x' Or, where the user fails to pass a value at all: $ /usr/bin/foo -n Usage: foo [options] foo: error: -n option requires an argument
If Putting it all together¶Here’s what
from optparse import OptionParser ... def main(): usage = "usage: %prog [options] arg" parser = OptionParser(usage) parser.add_option("-f", "--file", dest="filename", help="read data from FILENAME") parser.add_option("-v", "--verbose", action="store_true", dest="verbose") parser.add_option("-q", "--quiet", action="store_false", dest="verbose") ... (options, args) = parser.parse_args() if len(args) != 1: parser.error("incorrect number of arguments") if options.verbose: print("reading %s..." % options.filename) ... if __name__ == "__main__": main() Reference Guide¶Creating the parser¶The first step in using optparse. OptionParser (...)¶The OptionParser constructor has no required arguments, but a number of optional keyword arguments. You should always pass them as keyword arguments, i.e. do not rely on the order in which the arguments are declared. usage (default:
"%prog [options]" )The usage summary to print when your program is run incorrectly or with a help option. When option_list (default: [] )A list of Option objects to populate the parser with. The options in option_class (default: optparse.Option)Class to use when adding options to the parser in version (default: None )A version string to print when the user supplies a version option. If you supply a true value for conflict_handler (default:
"error" )Specifies what to do when options with conflicting option strings are added to the parser; see section Conflicts between options. description (default: None )A paragraph of text giving a brief overview of your program.
formatter (default: a new IndentedHelpFormatter )An instance of optparse.HelpFormatter that will be used for printing help text.
add_help_option (default: True )If true, prog The string to use when expanding epilog (default: None )A paragraph of help text to print after the option help. Populating the parser¶There are several ways to populate the parser with options. The preferred way is by using
The other alternative is to pass a list of pre-constructed Option instances to the OptionParser constructor, as in: option_list = [ make_option("-f", "--filename", action="store", type="string", dest="filename"), make_option("-q", "--quiet", action="store_false", dest="verbose"), ] parser = OptionParser(option_list=option_list) ( Defining options¶Each Option instance represents a set of synonymous command-line option strings, e.g. The
canonical way to create an OptionParser. add_option (option)¶
OptionParser. add_option (*opt_str, attr=value, ...)To define an option with only a short option string: parser.add_option("-f", attr=value, ...) And to define an option with only a long option string: parser.add_option("--foo", attr=value, ...) The keyword arguments define attributes of the new Option object. The most important option attribute is
An option’s action determines what "store" store this option’s argument (default) "store_const" store a constant value "store_true" store "store_false" store "append" append this option’s argument to a list "append_const" append a constant value to a list "count" increment a counter by one "callback" call a specified function "help" print a usage message including all options and the documentation for them (If you don’t supply an action, the default is As you can see, most actions
involve storing or updating a value somewhere. For example, when you call one of the first things If one of the options in this parser is defined with parser.add_option("-f", "--file", action="store", type="string", dest="filename") and the command-line being parsed includes any of the following: -ffoo -f foo --file=foo --file foo then The Option attributes¶The following option attributes may be passed as keyword arguments to
Option. action ¶(default: Determines Option. type ¶(default: The argument type expected by this option (e.g., Option. dest ¶(default: derived from option strings) If the option’s action implies writing or modifying a value somewhere, this tells
Option. default ¶The value to use for this option’s destination if the option is not
seen on the command line. See also Option. nargs ¶(default: 1) How many arguments of type
Option. const ¶For actions that store a constant value, the constant value to store. Option. choices ¶For options of type Option. callback ¶For options
with action Option. callback_args ¶ Option. callback_kwargs ¶Additional positional and keyword arguments to pass to Option. help ¶Help text to print for this option when listing all available options after the user supplies a Option. metavar ¶(default: derived from option strings) Stand-in for the option argument(s) to use when printing help text. See section Tutorial for an example. Standard option actions¶The various option actions all have slightly different requirements and effects.
Most actions have several relevant option attributes which you may specify to guide
Standard option types¶
Arguments to string options are not checked or converted in any way: the text on the command line is stored in the destination (or passed to the callback) as-is. Integer arguments (type
The conversion is done by calling
Parsing arguments¶The whole point of creating and populating an OptionParser is to call its (options, args) = parser.parse_args(args=None, values=None) where the input parameters are args
the list of arguments to process (default: values an and the return values are options the same object that was passed in as args the leftover positional arguments after all options have been processed The most common usage is to supply neither keyword argument. If you supply If Querying and manipulating your option parser¶The default behavior of the option parser can be customized slightly, and you can also poke around your option parser and see what’s there. OptionParser provides several methods to help you out: OptionParser. disable_interspersed_args ()¶Set parsing to stop on the first non-option. For example, if and treats it as equivalent to To disable this feature, call Use this if you have a command processor which runs another command which has options of its own and you want to make sure these options don’t get confused. For example, each command might have a different set of options. OptionParser. enable_interspersed_args ()¶Set parsing to not stop on the first non-option, allowing interspersing switches with command arguments. This is the default behavior. OptionParser. get_option (opt_str)¶Returns the Option instance with the option string opt_str, or OptionParser. has_option (opt_str)¶Return OptionParser. remove_option (opt_str)¶If the Conflicts between options¶If you’re not careful, it’s easy to define options with conflicting option strings: parser.add_option("-n", "--dry-run", ...) ... parser.add_option("-n", "--noisy", ...) (This is particularly true if you’ve defined your own OptionParser subclass with some standard options.) Every time you add an option,
parser = OptionParser(..., conflict_handler=handler) or with a separate call: parser.set_conflict_handler(handler) The available conflict handlers are:
As an example, let’s define an parser = OptionParser(conflict_handler="resolve") parser.add_option("-n", "--dry-run", ..., help="do no harm") parser.add_option("-n", "--noisy", ..., help="be noisy") At this point,
Options: --dry-run do no harm ... -n, --noisy be noisy It’s possible to whittle away the option strings for a previously added option until there are none left, and the user has no way of invoking that option from the command-line. In that case, parser.add_option("--dry-run", ..., help="new dry-run option") At this point, the original Options: ... -n, --noisy be noisy --dry-run new dry-run option Cleanup¶OptionParser instances have several cyclic references. This should not be a problem for Python’s garbage collector, but you may wish to break the cyclic references explicitly by calling Other methods¶OptionParser supports several other public methods: OptionParser. set_usage (usage)¶Set the usage string according to the rules described above for the OptionParser. print_usage (file=None)¶Print the usage message for the current program ( OptionParser. get_usage ()¶Same as OptionParser. set_defaults (dest=value, ...)¶Set default values for several option destinations at once. Using
parser.add_option("--advanced", action="store_const", dest="mode", const="advanced", default="novice") # overridden below parser.add_option("--novice", action="store_const", dest="mode", const="novice", default="advanced") # overrides above setting To avoid this confusion, use
parser.set_defaults(mode="advanced") parser.add_option("--advanced", action="store_const", dest="mode", const="advanced") parser.add_option("--novice", action="store_const", dest="mode", const="novice") Option Callbacks¶When
There are two steps to defining a callback option:
Defining a callback option¶As always, the easiest way to define a callback option is by using the
parser.add_option("-c", action="callback", callback=my_callback)
def my_callback(option, opt, value, parser): The four arguments to a callback are described below. There are several other option attributes that you can supply when you define a callback option: type has its usual meaning: as with the nargs also has its usual meaning: if it is supplied and > 1, callback_args a tuple of extra positional arguments to pass to the callback callback_kwargs a dictionary of extra keyword arguments to pass to the callback How callbacks are called¶All callbacks are called as follows: func(option, opt_str, value, parser, *args, **kwargs) where option is the Option instance that’s calling the callback opt_str is the option string seen on the command-line that’s
triggering the callback. (If an abbreviated long option was used, value is the argument to this option seen on the command-line. parser is the OptionParser instance driving the whole thing, mainly useful because you can access some other interesting data through its instance attributes: parser.largs the current list of leftover arguments, ie. arguments that have been consumed
but are neither options nor option arguments. Feel free to modify parser.rargs the current list of remaining arguments, ie. with parser.values the object where option values are by
default stored (an instance of optparse.OptionValues). This lets callbacks use the same mechanism as the rest of args
is a tuple of arbitrary positional arguments supplied via the kwargs is a dictionary of arbitrary keyword arguments supplied via Raising errors in a callback¶The callback function should raise Callback example 1: trivial callback¶Here’s an example of a callback option that takes no arguments, and simply records that the option was seen: def record_foo_seen(option, opt_str, value, parser): parser.values.saw_foo = True parser.add_option("--foo", action="callback", callback=record_foo_seen) Of course, you could do that with the Callback example 2: check option order¶Here’s a slightly more interesting example: record the fact that def check_order(option, opt_str, value, parser): if parser.values.b: raise OptionValueError("can't use -a after -b") parser.values.a = 1 ... parser.add_option("-a", action="callback", callback=check_order) parser.add_option("-b", action="store_true", dest="b") Callback example 3: check option order (generalized)¶If you want to re-use this callback for several similar options (set a flag, but blow up if def check_order(option, opt_str, value, parser): if parser.values.b: raise OptionValueError("can't use %s after -b" % opt_str) setattr(parser.values, option.dest, 1) ... parser.add_option("-a", action="callback", callback=check_order, dest='a') parser.add_option("-b", action="store_true", dest="b") parser.add_option("-c", action="callback", callback=check_order, dest='c') Callback example 4: check arbitrary condition¶Of course, you could put any condition in there—you’re not limited to checking the values of already-defined options. For example, if you have options that should not be called when the moon is full, all you have to do is this: def check_moon(option, opt_str, value, parser): if is_moon_full(): raise OptionValueError("%s option invalid when moon is full" % opt_str) setattr(parser.values, option.dest, 1) ... parser.add_option("--foo", action="callback", callback=check_moon, dest="foo") (The definition of Callback example 5: fixed arguments¶Things get slightly more interesting
when you define callback options that take a fixed number of arguments. Specifying that a callback option takes arguments is similar to defining a Here’s an example that just emulates the standard def store_value(option, opt_str, value, parser): setattr(parser.values, option.dest, value) ... parser.add_option("--foo", action="callback", callback=store_value, type="int", nargs=3, dest="foo") Note that
Callback example 6: variable arguments¶Things get hairy when you want an option to take a variable number of arguments. For this case, you must write a callback, as
If you want an option that takes a variable number of arguments, there are several subtle, tricky issues to worry about. The exact implementation you choose will be based on which trade-offs you’re willing to make for your application (which
is why Nevertheless, here’s a stab at a callback for an option with variable arguments: def vararg_callback(option, opt_str, value, parser): assert value is None value = [] def floatable(str): try: float(str) return True except ValueError: return False for arg in parser.rargs: # stop on --foo like options if arg[:2] == "--" and len(arg) > 2: break # stop on -a, but not on -3 or -3.0 if arg[:1] == "-" and len(arg) > 1 and not floatable(arg): break value.append(arg) del parser.rargs[:len(value)] setattr(parser.values, option.dest, value) ... parser.add_option("-c", "--callback", dest="vararg_attr", action="callback", callback=vararg_callback) Extending optparse¶Since the two major controlling factors in how
Adding new types¶To add new types, you need to define your own subclass of Option. TYPES ¶A tuple of type names; in your subclass, simply define a new tuple Option. TYPE_CHECKER ¶A dictionary mapping type names to type-checking functions. A type-checking function has the following signature: def check_mytype(option, opt, value) where Your type-checking function should raise Here’s a silly example that demonstrates adding a First, the necessary imports: from copy import copy from optparse import Option, OptionValueError You need to define your type-checker first, since it’s referred to later (in the
def check_complex(option, opt, value): try: return complex(value) except ValueError: raise OptionValueError( "option %s: invalid complex value: %r" % (opt, value)) Finally, the Option subclass: class MyOption (Option): TYPES = Option.TYPES + ("complex",) TYPE_CHECKER = copy(Option.TYPE_CHECKER) TYPE_CHECKER["complex"] = check_complex (If we didn’t make a That’s it! Now you can write a script that uses the new option type just like any other parser = OptionParser(option_class=MyOption) parser.add_option("-c", type="complex") Alternately, you can build your own option list and pass it to OptionParser; if you don’t use option_list = [MyOption("-c", action="store", type="complex", dest="c")] parser = OptionParser(option_list=option_list) Adding new actions¶Adding new actions is a bit trickier, because you have to understand that actions that result in
actions
that take a value from the command line and expect it to be of a certain type; or rather, a string that can be converted to a certain type. These options require a These are overlapping sets: some default “store” actions are When you add an action, you need to categorize it by listing it in at least one of the following class attributes of Option (all are lists of strings): Option. ACTIONS ¶All actions must be listed in ACTIONS. Option. STORE_ACTIONS ¶“store” actions are additionally listed here. Option. TYPED_ACTIONS ¶“typed” actions are additionally listed here. Option. ALWAYS_TYPED_ACTIONS ¶Actions that always take a type (i.e. whose options always take a value) are additionally listed here. The only effect of this is that
In order to actually implement your new action,
you must override Option’s For example, let’s add an --names=foo,bar --names blah --names ding,dong would result in a list ["foo", "bar", "blah", "ding", "dong"] Again we define a subclass of Option: class MyOption(Option): ACTIONS = Option.ACTIONS + ("extend",) STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",) TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",) ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",) def take_action(self, action, dest, opt, value, values, parser): if action == "extend": lvalue = value.split(",") values.ensure_value(dest, []).extend(lvalue) else: Option.take_action( self, action, dest, opt, value, values, parser) Features of note:
How do you make a menu list in Python?The Menu widget is used to create various types of menus (top level, pull down, and pop up) in the python application.. # !/usr/bin/python3.. from tkinter import *. top = Tk(). def hello():. print("hello!"). # create a toplevel menu.. menubar = Menu(root). menubar.add_command(label="Hello!", command=hello). How do you make a choice input in Python?You have to first get the keyboard input by calling the input() function. Then evaluate the choice by using the if-elif-else structure. value1 = input("Please enter first integer:\n") value2 = input("Please enter second integer:\n") v1 = int(value1) v2 = int(value2) choice = input("Enter 1 for addition.
How do you select between two options in Python?This randomly gives you either one of each of the elements in str_a , str_b , str_c , str_d , str_e , str_f or it gives you str_g + random. choice(str_h) . Or perhaps ''. join(random_choice(s) for s in (str_a, str_b, str_c, str_d, str_e, str_f)) .
|