How to use optional command line arguments in a python function? - python

I want a more compact and scalable way to use command line args to feed a python function, here is what i have:
def getRelevant (number = 5, sortBy = "Change"):
number, sortBy = int(number), sortBy
relevant = ...
return relevant
if __name__ == "__main__":
if len(sys.argv) == 3:
print(getRelevant(sys.argv[1], sys.argv[2]))
elif len(sys.argv) == 2:
print(getRelevant(sys.argv[1]))
else:
print(getRelevant())
It works. But I'm not happy with this conditionals, is there a way to make it simpler?

Argparse should do this. It is feature rich and flexible.
For your case, the below does the job:
import argparse
parser = argparse.ArgumentParser(description='Description of your app here.')
parser.add_argument('-N', '--integers', default=5, help='your help text here')
parser.add_argument('-S', '--sortby', default='Change', choices=['Change', 'SomeOtherOption'], help='some help text here ')
if __name__ == "__main__":
args = parser.parse_args()
print(args.integers) # prints 5 if nothing provided
print(args.sortby) # prints 'Change' if nothing provided

You can try with argparse or Typer
argparse: https://docs.python.org/3/library/argparse.html
typer: https://typer.tiangolo.com/

argparse is of course the tool you want to learn for commandline options and arguments - it's part of the tools alls devs should know about (with logging and pdb).
This being said, for this exact case, you could also solve the issue very simply without argparse:
if __name__ == "__main__":
args = sys.argv[1:]
print(getRelevant(*args))

Related

unittest for command line arguments

How do I unit test my script for incorrect command line arguments?
For example,
my_script.py -t
should give an error since -t flag is not present, as shown in the code below:
parser = OptionParser()
parser.add_option("-d",
action="callback",
callback=get_bios_difference,
help="Check difference between two files"
)
(options, args) = parser.parse_args()
if len(sys.argv) == 1: # if only 1 argument, it's the script name
parser.print_help()
exit()
First, you need a unit to test:
def parse_options(args=None):
# Duplicating the default behavior of OptionParser.parse_args
if args is None:
args = sys.argv[1:]
parser = OptionParser()
parser.add_option("-d",
action="callback",
callback=get_bios_difference,
help="Check difference between two files"
)
(options, args) = parser.parse_args(args)
if not args:
parser.print_help()
exit()
Note that we explicitly pass args to parse_args, rather than let it assume sys.argv is to be parsed.
In production, you can call parse_options() and it will work as before. For testing, you can call parse_options([]) or parse_options(["-t"]) or whatever other combination of arguments you want to test.
All that said, you should be using argparse instead of optparse (which has been deprecated for years) in new code.
OptionParser
Deprecated since version 2.7: The optparse module is deprecated and will not be developed further; development will continue with the argparse module.
your questions has nothing to do with unittest? there is no need to assert, the nargs=2 defined 2 items needed for --d.
argparse will check the number of args for you, here is parameter.py
import argparse
from pprint import pprint
def get_parser():
parser = argparse.ArgumentParser(description='example of argparse')
parser.add_argument('--d', type=str, nargs=2, help='2 files')
return parser
if __name__ == '__main__':
parser = get_parser()
args = parser.parse_args(sys.argv[1:])
pprint(args)
run with 2 files:
parameter.py --d a b
Namespace(d=['a', 'b'])
When run with 1 parameter
parameter.py --d a
parameter.py: error: argument --d: expected 2 argument(s)

Parsing cmd args like typical filter programs

I spent few hours reading tutorials about argparse and managed to learn to use normal parameters. The official documentation is not very readable to me. I'm new to Python. I'm trying to write a program that could be invoked in following ways:
cat inFile | program [options] > outFile -- If no inFile or outfile is specified, read from stdin and output to stdout.
program [options] inFile outFile
program [options] inFile > outFile -- If only one file is specified it is input and output should go to stdout.
cat inFile | program [options] - outFile -- If '-' is given in place of inFlie read from stdin.
program [options] /path/to/folder outFile -- Process all files from /path/to/folder and it subdirectories.
I want it to behave like regular cli program under GNU/Linux.
It would be also nice if the program would be able to be invoked:
program [options] inFile0 inFile1 ... inFileN outFile -- first path/file always interpreted as input, last one always interpreted as output. Any additional ones interpreted as inputs.
I could probably write dirty code that would accomplish this but this is going to be used, so someone will end up maintaining it (and he will know where I live...).
Any help/suggestions are much appreciated.
Combining answers and some more knowledge from the Internet I've managed to write this(it does not accept multiple inputs but this is enough):
import sys, argparse, os.path, glob
def inputFile(path):
if path == "-":
return [sys.stdin]
elif os.path.exists(path):
if os.path.isfile(path):
return [path]
else:
return [y for x in os.walk(path) for y in glob.glob(os.path.join(x[0], '*.dat'))]
else:
exit(2)
def main(argv):
cmdArgsParser = argparse.ArgumentParser()
cmdArgsParser.add_argument('inFile', nargs='?', default='-', type=inputFile)
cmdArgsParser.add_argument('outFile', nargs='?', default='-', type=argparse.FileType('w'))
cmdArgs = cmdArgsParser.parse_args()
print cmdArgs.inFile
print cmdArgs.outFile
if __name__ == "__main__":
main(sys.argv[1:])
Thank you!
You need a positional argument (name not starting with a dash), optional arguments (nargs='?'), a default argument (default='-'). Additionally, argparse.FileType is a convenience factory to return sys.stdin or sys.stdout if - is passed (depending on the mode).
All together:
#!/usr/bin/env python
import argparse
# default argument is sys.argv[0]
parser = argparse.ArgumentParser('foo')
parser.add_argument('in_file', nargs='?', default='-', type=argparse.FileType('r'))
parser.add_argument('out_file', nargs='?', default='-', type=argparse.FileType('w'))
def main():
# default argument is is sys.argv[1:]
args = parser.parse_args(['bar', 'baz'])
print(args)
args = parser.parse_args(['bar', '-'])
print(args)
args = parser.parse_args(['bar'])
print(args)
args = parser.parse_args(['-', 'baz'])
print(args)
args = parser.parse_args(['-', '-'])
print(args)
args = parser.parse_args(['-'])
print(args)
args = parser.parse_args([])
print(args)
if __name__ == '__main__':
main()
I'll give you a start script to play with. It uses optionals rather than positionals. and only one input file. But it should give a taste of what you can do.
import argparse
parser = argparse.ArgumentParser()
inarg = parser.add_argument('-i','--infile', type=argparse.FileType('r'), default='-')
outarg = parser.add_argument('-o','--outfile', type=argparse.FileType('w'), default='-')
args = parser.parse_args()
print(args)
cnt = 0
for line in args.infile:
print(cnt, line)
args.outfile.write(line)
cnt += 1
When called without arguments, it just echos your input (after ^D). I'm a little bothered that it doesn't exit until I issue another ^D.
FileType is convenient, but has the major fault - it opens the files, but you have to close them yourself, or let Python do so when exiting. There's also the complication that you don't want to close stdin/out.
The best argparse questions include a basic script, and specific questions on how to correct or improve it. Your specs are reasonably clear. but it would be nice if you gave us more to work with.
To handle the subdirectories option, I would skip the FileType bit. Use argparse to get 2 lists of strings (or a list and an name), and then do the necessary chgdir and or glob to find and iterate over files. Don't expect argparse to do the actual work. Use it to parse the commandline strings. Here a sketch of such a script, leaving most details for you to fill in.
import argparse
import os
import sys # of stdin/out
....
def open_output(outfile):
# function to open a file for writing
# should handle '-'
# return a file object
def glob_dir(adir):
# function to glob a dir
# return a list of files ready to open
def open_forread(afilename):
# function to open file for reading
# be sensitive to '-'
def walkdirs(alist):
outlist = []
for name in alist:
if <name is file>;
outlist.append(name)
else <name is a dir>:
glist = glob(dir)
outlist.extend(glist)
else:
<error>
return outlist
def cat(infile, outfile):
<do your thing here>
def main(args):
# handle args options
filelist = walkdirs(args.inlist)
fout = open_outdir(args.outfile)
for name in filelist:
fin = open_forread(name)
cat(fin,fout)
if <fin not stdin>: fin.close()
if <fout not stdout>: fout.close()
if '__name__' == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('inlist', nargs='*')
parser.add_argument('outfile')
# add options
args = parser.parse_args()
main(args)
The parser here requires you to give it an outfile name, even if it is '-'. I could define its nargs='?' to make it optional. But that does not play nicely with the 'inlist` '*'.
Consider
myprog one two three
Is that
namespace(inlist=['one','two','three'], outfile=default)
or
namespace(inlist=['one','two'], outfile='three')
With both a * and ? positional, the identity of the last string is ambiguous - is it the last entry for inlist, or the optional entry for outfile? argparse chooses the former, and never assigns the value to outfile.
With --infile, --outfile definitions, the allocation of these strings is clear.
In sense this problem is too complex for argparse - there's nothing in it to handle things like directories. In another sense it is too simple. You could just as easily split sys.argv[1:] between inlist and outfile without the help of argparse.

Optparse Option Actions

I'm working with optparse, and I'm writing a script with 3 commandline arguments. The first one (-qtype) specifies whether information needs to be called from a local file, or from the web. Then depending on this, the 2nd argument (-qname) is either a string of nucleotides, or a FASTA filename. The 3rd argument (-output) is the output filename.
My question is if there is an optparse option action that I can use for the 1st argument (since the standard "store," "append," etc do not apply in this case).
Here is what I have so far: (it is likely laced with errors)
import optparse
if False:#__name__== '__main__':
# parser object for managing input options
parser = optparse.OptionParser()
parser.add_option( '-qtype' , action = ‘?’ )
parser.add_option( '-qname' , action = ‘?’ , […] )
parser.add_option( '-output' , action = ‘store’ , type = ‘?’ , dest = ‘filename’ )
# load the inputs
args = [‘-qtype’ , ‘-qname’ , ‘-output’]
(options , args) = parser.parse_args()
I have question marks and [...] where I am boggled over how to approach this problem.
Option 1: Use arguments instead of options
This might be a viable approach since it seems you might require all three inputs from the user to run normally.
According to the optparse docs
A program should be able to run just fine with no options whatsoever
In this case your solution would like
import optparse
import sys
if __name__ == '__main__':
parser = optparse.OptionParser()
(options, args) = parser.parse_args()
if len(args) != 3:
print 'please specify all required arguments - qtype qname output_file'
sys.exit(-1)
qtype, qname, output = args
if qtype == 'web':
pass
elif qtype == 'local':
pass
else:
print 'no qtype specified! exiting'
sys.exit(-1)
Then you can use all the arguments as strings and either process them directly or turn them into files / url for web requests.
Example command line:
program.py web blah blah
Option 2: Use options anyway
import optparse
import sys
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('--qtype', action='store', dest='qtype', type='string')
parser.add_option('--qname', action='store', dest='qname', type='string')
parser.add_option('--output', action='store', type='string', dest='filename')
(options, args) = parser.parse_args()
if options.qtype == 'web':
pass
elif options.qtype == 'local':
pass
else:
print 'no qtype specified! exiting'
sys.exit(-1)
Example usage:
program.py --qtype web --qname blah --output blah

Display help message with Python argparse when script is called without any arguments

Assume I have a program that uses argparse to process command line arguments/options. The following will print the 'help' message:
./myprogram -h
or:
./myprogram --help
But, if I run the script without any arguments whatsoever, it doesn't do anything. What I want it to do is to display the usage message when it is called with no arguments. How is that done?
This answer comes from Steven Bethard on Google groups. I'm reposting it here to make it easier for people without a Google account to access.
You can override the default behavior of the error method:
import argparse
import sys
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
parser = MyParser()
parser.add_argument('foo', nargs='+')
args = parser.parse_args()
Note that the above solution will print the help message whenever the error
method is triggered. For example, test.py --blah will print the help message
too if --blah isn't a valid option.
If you want to print the help message only if no arguments are supplied on the
command line, then perhaps this is still the easiest way:
import argparse
import sys
parser=argparse.ArgumentParser()
parser.add_argument('foo', nargs='+')
if len(sys.argv)==1:
parser.print_help(sys.stderr)
sys.exit(1)
args=parser.parse_args()
Note that parser.print_help() prints to stdout by default. As init_js suggests, use parser.print_help(sys.stderr) to print to stderr.
Instead of writing a class, a try/except can be used instead
try:
options = parser.parse_args()
except:
parser.print_help()
sys.exit(0)
The upside is that the workflow is clearer and you don't need a stub class. The downside is that the first 'usage' line is printed twice.
This will need at least one mandatory argument. With no mandatory arguments, providing zero args on the commandline is valid.
With argparse you could use ArgumentParser.print_usage():
parser.argparse.ArgumentParser()
# parser.add_args here
# sys.argv includes a list of elements starting with the program
if len(sys.argv) < 2:
parser.print_usage()
sys.exit(1)
Printing help
ArgumentParser.print_usage(file=None)
  Print a brief description of how the ArgumentParser should be invoked on the command line. If file is None, sys.stdout is assumed.
The cleanest solution will be to manually pass default argument if none were given on the command line:
parser.parse_args(args=None if sys.argv[1:] else ['--help'])
Complete example:
import argparse, sys
parser = argparse.ArgumentParser()
parser.add_argument('--host', default='localhost', help='Host to connect to')
# parse arguments
args = parser.parse_args(args=None if sys.argv[1:] else ['--help'])
# use your args
print("connecting to {}".format(args.host))
This will print complete help (not short usage) if called w/o arguments.
If you associate default functions for (sub)parsers, as is mentioned under add_subparsers, you can simply add it as the default action:
parser = argparse.ArgumentParser()
parser.set_defaults(func=lambda x: parser.print_usage())
args = parser.parse_args()
args.func(args)
Add the try-except if you raise exceptions due to missing positional arguments.
If you have arguments that must be specified for the script to run - use the required parameter for ArgumentParser as shown below:-
parser.add_argument('--foo', required=True)
parse_args() will report an error if the script is run without any arguments.
Throwing my version into the pile here:
import argparse
parser = argparse.ArgumentParser()
args = parser.parse_args()
if not vars(args):
parser.print_help()
parser.exit(1)
You may notice the parser.exit - I mainly do it like that because it saves an import line if that was the only reason for sys in the file...
There are a pair of one-liners with sys.argv[1:] (a very common Python's idiom to refer the command line arguments, being sys.argv[0] the script's name) that can do the job.
The first one is self-explanatory, clean and pythonic:
args = parser.parse_args(None if sys.argv[1:] else ['-h'])
The second one is a little hackier. Combining the previously evaluated fact that an empty list is False with the True == 1 and False == 0 equivalences you get this:
args = parser.parse_args([None, ['-h']][not sys.argv[1:]])
Maybe too many brackets, but pretty clear if a previous argument selection was made.
_, *av = sys.argv
args = parser.parse_args([None, ['-h']][not av])
parser.print_help()
parser.exit()
The parser.exit method also accept a status (returncode), and a message value (include a trailing newline yourself!).
an opinionated example,
:)
#!/usr/bin/env python3
""" Example argparser based python file
"""
import argparse
ARGP = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawTextHelpFormatter,
)
ARGP.add_argument('--example', action='store_true', help='Example Argument')
def main(argp=None):
if argp is None:
argp = ARGP.parse_args() # pragma: no cover
if 'soemthing_went_wrong' and not argp.example:
ARGP.print_help()
ARGP.exit(status=64, message="\nSomething went wrong, --example condition was not set\n")
if __name__ == '__main__':
main() # pragma: no cover
Example calls:
$ python3 ~/helloworld.py; echo $?
usage: helloworld.py [-h] [--example]
Example argparser based python file
optional arguments:
-h, --help show this help message and exit
--example Example Argument
Something went wrong, --example condition was not set
64
$ python3 ~/helloworld.py --example; echo $?
0
Most of the answers here required another module, such as sys, to be imported or were using optional arguments. I wanted to discover an answer that used only argparse, worked with required arguments, and if possible worked without catching exceptions. I ended up with the following:
import argparse
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(add_help=False)
arg_parser.add_argument('input_file', type=str, help='The path to the input file.')
arg_parser.add_argument('output_file', type=str, help='The path to the output file.')
arg_parser.add_argument('-h','--help', action='store_true', help='show this help message and exit')
arg_parser.usage = arg_parser.format_help()
args = arg_parser.parse_args()
The main idea was to use the format_help function in order to provide the help string to the usage statement. Setting add_help to False in the call to ArgumentParser() prevents the help statement from printing twice in certain circumstances. However, I had to create an argument for the optional help argument that mimicked the typical help message once it was set to False in order to display the optional help argument in the help message. The action is set to store_true in the help argument to prevent the help message from filling in a value like HELP for the parameter when it prints the help message.
So for a really simple answer. Most of the time with argparse you are checking to see if parameters are set anyway, to call a function that does something.
If no parameters, just else out at the end and print the help. Simple and works.
import argparse
import sys
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("--holidays", action='store_true')
group.add_argument("--people", action='store_true')
args=parser.parse_args()
if args.holidays:
get_holidays()
elif args.people:
get_people()
else:
parser.print_help(sys.stderr)
Here is another way to do it, if you need something flexible where you want to display help if specific params are passed, none at all or more than 1 conflicting arg:
import argparse
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--days', required=False, help="Check mapped inventory that is x days old", default=None)
parser.add_argument('-e', '--event', required=False, action="store", dest="event_id",
help="Check mapped inventory for a specific event", default=None)
parser.add_argument('-b', '--broker', required=False, action="store", dest="broker_id",
help="Check mapped inventory for a broker", default=None)
parser.add_argument('-k', '--keyword', required=False, action="store", dest="event_keyword",
help="Check mapped inventory for a specific event keyword", default=None)
parser.add_argument('-p', '--product', required=False, action="store", dest="product_id",
help="Check mapped inventory for a specific product", default=None)
parser.add_argument('-m', '--metadata', required=False, action="store", dest="metadata",
help="Check mapped inventory for specific metadata, good for debugging past tix", default=None)
parser.add_argument('-u', '--update', required=False, action="store_true", dest="make_updates",
help="Update the event for a product if there is a difference, default No", default=False)
args = parser.parse_args()
days = args.days
event_id = args.event_id
broker_id = args.broker_id
event_keyword = args.event_keyword
product_id = args.product_id
metadata = args.metadata
make_updates = args.make_updates
no_change_counter = 0
change_counter = 0
req_arg = bool(days) + bool(event_id) + bool(broker_id) + bool(product_id) + bool(event_keyword) + bool(metadata)
if not req_arg:
print("Need to specify days, broker id, event id, event keyword or past tickets full metadata")
parser.print_help()
sys.exit()
elif req_arg != 1:
print("More than one option specified. Need to specify only one required option")
parser.print_help()
sys.exit()
# Processing logic here ...
Cheers!
I like to keep things as simple as possible, this works great:
#!/usr/bin/env python3
Description = """Tool description"""
Epilog = """toolname.py -a aflag -b bflag with these combined it does blah"""
arg_parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=Description,
epilog=Epilog,
)
try:
if len(sys.argv) == 1:
arg_parser.print_help()
except Exception as e:
print(e)
This is how I start all my tools as its always good to include some examples
When call add_subparsers method save the first positional argument to dest= and check value after argparse has been initialized, like this:
subparsers = parser.add_subparsers(dest='command')
And just check this this variable:
if not args.command:
parser.print_help()
parser.exit(1) # If exit() - exit code will be zero (no error)
Full example:
#!/usr/bin/env python
""" doc """
import argparse
import sys
parser = argparse.ArgumentParser(description=__doc__)
subparsers = parser.add_subparsers(dest='command',
help='List of commands')
list_parser = subparsers.add_parser('list',
help='List contents')
list_parser.add_argument('dir', action='store',
help='Directory to list')
create_parser = subparsers.add_parser('create',
help='Create a directory')
create_parser.add_argument('dirname', action='store',
help='New directory to create')
create_parser.add_argument('--read-only', default=False, action='store_true',
help='Set permissions to prevent writing to the directory')
args = parser.parse_args()
if not args.command:
parser.print_help()
parser.exit(1)
print(vars(args)) # For debug
This approach is a lot more elegant than most others. Instead of overriding error(), you can control the behaviour a lot more precisely by wrapping the parse_args() method:
import sys
import argparse
HelpFlags = ('help', '--help', '-h', '/h', '?', '/?', )
class ArgParser (argparse.ArgumentParser):
def __init__(self, *args, **kws):
super().__init__(*args, **kws)
def parse_args(self, args=None, namespace=None):
if args is None:
args = sys.argv[1:]
if len(args) < 1 or (args[0].lower() in HelpFlags):
self.print_help(sys.stderr)
sys.exit()
return super().parse_args(args, namespace)
Set your positional arguments with nargs, and check if positional args are empty.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?')
args = parser.parse_args()
if not args.file:
parser.print_help()
Reference Python nargs
If your command is something where a user needs to choose some action, then use a mutually exclusive group with required=True.
This is kind of an extension to the answer given by pd321.
import argparse
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--batch", action='store', type=int, metavar='pay_id')
group.add_argument("--list", action='store_true')
group.add_argument("--all", action='store_true', help='check all payments')
args=parser.parse_args()
if args.batch:
print('batch {}'.format(args.batch))
if args.list:
print('list')
if args.all:
print('all')
Output:
$ python3 a_test.py
usage: a_test.py [-h] (--batch pay_id | --list | --all)
a_test.py: error: one of the arguments --batch --list --all is required
This only give the basic help. And some of the other answers will give you the full help. But at least your users know they can do -h
This isn't good (also, because intercepts all errors), but:
def _error(parser):
def wrapper(interceptor):
parser.print_help()
sys.exit(-1)
return wrapper
def _args_get(args=sys.argv[1:]):
parser = argparser.ArgumentParser()
parser.error = _error(parser)
parser.add_argument(...)
...
Here is definition of the error function of the ArgumentParser class.
As you see, the following signature takes two arguments. However, functions outside the class know nothing about first argument self, because, roughly speaking, this argument is for the class.
def _error(self, message):
self.print_help()
sys.exit(-1)
def _args_get(args=sys.argv[1:]):
parser = argparser.ArgumentParser()
parser.error = _error
...
will output:
"AttributeError: 'str' object has no attribute 'print_help'"
You can pass parser (self) in _error function, by calling it:
def _error(self, message):
self.print_help()
sys.exit(-1)
def _args_get(args=sys.argv[1:]):
parser = argparser.ArgumentParser()
parser.error = _error(parser)
...
But if you don't want exit the program right now, return it:
def _error(parser):
def wrapper():
parser.print_help()
sys.exit(-1)
return wrapper
Nonetheless, parser doesn't know that it has been modified. Thus, when an error occurs, it will print the cause of it (by the way, it's a localized translation). So intercept it:
def _error(parser):
def wrapper(interceptor):
parser.print_help()
sys.exit(-1)
return wrapper
Now, when an error occurs, parser will print the cause of it, and you'll intercept it, look at it, and... throw out.

To understand Python's optparse

Thank you for quack in pointing out the off-by-one!
The following code is my first attempt in writing code with Optparse.
How can you fix the following bug in getting the help by Optparse?
#!/usr/bin/env python
import sys
import os
from optparse import OptionParser
e = sys.argv[1]
b = sys.argv[2]
no = sys.argv[3]
def set_figu(figu):
sum = 777
return sum
def main():
usage = "Usage: negative_bin_base.py <eksponentti> <siirre> <figu>"
parser = OptionParser(usage)
parser.add_option("-h", "--help", dest="help",
help="get synopsis of parameters")
# print the output of the work-horse
print set_figu(no)
(options, args) = parser.parse_args()
if len(args) < 4:
parser.error("incorrect number of arguments")
if options.informative:
print "reading %s..." % options.help
if __name__ == "__main__":
main()
Example of wrong output with correct number of parameters
python negative_bin_base.py 13 13 332
Traceback (most recent call last):
File "negative_bin_base.py", line 37, in <module>
main()
File "negative_bin_base.py", line 26, in main
help="get synopsis of parameters")
File "/usr/lib/python2.6/optparse.py", line 1020, in add_option
self._check_conflict(option)
File "/usr/lib/python2.6/optparse.py", line 995, in _check_conflict
option)
optparse.OptionConflictError: option -h/--help: conflicting option string(s): -h, --help
Constructor for class optparse.OptionParser(...) has optional named parameter 'add_help_option', which defaults to 'True'. You will have to explicitly reject default help option and message, if you want to provide your own.
parser = OptionParser(usage, add_help_option=False)
The bug is that your arguments array includes the name of the script as sys.argv[0]. Thus your if is off-by-one:
# python sys.argv[0] sys.argv[1] sys.argv[2] sys.argv[3]
if len(sys.argv) < 4:
sys.exit(usage)
This should do what you require, based on your example above:
#!/usr/bin/env python
from optparse import OptionParser
def main():
usage = "Usage: negative_bin_base.py <eksponentti> <siirre> <figu>"
parser = OptionParser(usage)
(options, args) = parser.parse_args()
if len(args) != 3:
parser.error("incorrect number of arguments")
e = args[0]
b = args[1]
no = args[2]
# ...
if __name__ == "__main__":
main()
For using optparse here's what I normally do:
separate command line parsing from your main code base for better modularization.
(Put the processing right after "if __name__ == "__main__"")
Let optparse handle your help.
(Use parser.print_help())
Use the optparse constructs, if you don't like them just parse sys.argv yourself.
(use add_option to define your necessary options)
Here's how I would write your sample using the optparse library:
def main():
print 'Welcome to the main event!'
if __name__ == '__main__':
import optparse
parser = optparse.OptionParser()
parser.add_option("-e", "--eksponentti", dest="eksponentti",
help="This is help for <eksponentti>.",
default=None)
parser.add_option("-s", "--siirre", dest="siirre",
help="This is help for <siirre>.",
default=None)
parser.add_option("-f", "--figu", dest="figu",
help="This is help for <figu>.",
default=None)
(options, args) = parser.parse_args()
if options.eksponentti and options.siirre and options.figu:
main()
else:
print "ERROR -- Expected Arguments not given!"
parser.print_help()
Running this without the necessary options will give the following output:
(It's a little prettier than I can format it here...)
ERROR -- Expected Arguments not given! Usage: parm.py [options]
Options:
-h, --help show this help message and exit
-e EKSPONENTTI, --eksponentti=EKSPONENTTI This is help for <eksponentti>.
-s SIIRRE, --siirre=SIIRRE This is help for <siirre>.
-f FIGU, --figu=FIGU This is help for <figu>.

Categories