optparse options

icarus rsarpi at gmail.com
Tue May 19 17:07:37 EDT 2009


Why do I need to put two options for this script to print the path?

if I just specify the option and argument...
$ python <script>.py -p xxxx
Usage: <script>.py [-p dir] [--part=dir]

<script>.py: error: No options specified

So I need to give it two arguments...
$ python <script>.py --part xxxx y
xxxx


Desired output:
$ python <script>.py --part xxxx
xxxx

$ python <script>.py --part xxxx y
Usage: <script>.py [-p dir] [--part=dir]
<script>.py: error: some message


----
#/usr/bin/python

import optparse

def main():
	parser = optparse.OptionParser(usage="%prog [-p dir] [--part=dir] ",
version="%prog 1.0")

	parser.add_option( "-p", "--part", dest="directory",
	                  help="process target directory", metavar="dir")
	(options, args) = parser.parse_args()

	if len(args) != 1:
		parser.error("No options specified")


	path = options.directory
	print path

if __name__ == "__main__":
	main()



More information about the Python-list mailing list