473,396 Members | 1,702 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

getopt

Hi,

I'm going over a script that demonstrates the getopt function. I include
the script here:
#! /usr/bin/python

import sys, getopt, string

def help_message():
print '''options.py -- uses getopt to recognize options
Options: -h -- displays this help message
-a -- expects an argument
--file= -- expects an argument
--view -- doesn't necessarily expect an argument
--version -- displays Python version'''
sys.exit(0)

try:
options, xarguments = getopt.getopt(sys.argv[1:], 'ha', \
['file=', 'view=', 'version', 'python-version'])
except getopt.error:
print '''Error: You tried to use an unknown option or the
argument for an option that requires it was missing. Try
`options.py -h\' for more information.'''
sys.exit(0)

for a in options[:]:
if a[0] == '-h':
help_message()

for a in options[:]:
if a[0] == '-a' and a[1] != '':
print a[0]+' = '+a[1]
options.remove(a)
break
elif a[0] == '-a' and a[1] == '':
print '-a expects an argument'
sys.exit(0)

for a in options[:]:
if a[0] == '--file' and a[1] != '':
print a[0]+' = '+a[1]
options.remove(a)
break
elif a[0] == '--file' and a[1] == '':
print '--file expects an argument'
sys.exit(0)

for a in options[:]:
if a[0] == '--view' and a[1] != '':
print a[0]+' = '+a[1]
options.remove(a)
break
elif a[0] == '--view' and a[1] == '':
print '--view doesn\'t necessarily expect an argument...'
options.remove(a)
sys.exit(0)

for a in options[:]:
if a[0] == '--version':
print 'options version 0.0.001'
sys.exit(0)

for a in options[:]:
if a[0] == '--python-version':
print 'Python '+sys.version
sys.exit(0)

# END OF SCRIPT

When I execute the script with the -a option or the --view option as in:

../script_name -a myarg

It should report back:

-a = myarg

Instead it gives me:

-a expects an argument

This goes the same for the --file argument. The only one that works as
it should is the --view argument, as in:

../help2.py --view=myarg
--view = ssdt

This is because an equal sign (=) has been appended to 'view' when
getopt is called. If I add an equal sign to file (file=), it starts
working as it should too.

Can anyone explain this?

--
Thanks,

Don
Jul 18 '05 #1
3 7004
Don Low wrote:
I'm going over a script that demonstrates the getopt function. I include
the script here:
I you are only now exploring the possibilities of getopt, you might want to
leapfrog and use the more powerful optparse module.
options, xarguments = getopt.getopt(sys.argv[1:], 'ha', \
['file=', 'view=', 'version', 'python-version'])


If you want the "a" option to require an argument, you have to append a
colon serving the same purpose as the "=" for long options:

options, xarguments = getopt.getopt(sys.argv[1:], 'ha:', \
['file=', 'view=', 'version', 'python-version'])
Peter
Jul 18 '05 #2
Don Low <m_*******@sympatico.ca> writes:
Hi,

I'm going over a script that demonstrates the getopt function. I include
the script here: [...] Can anyone explain this?


Sorry for not answering your question, but can't you just use optparse (comes
with python 2.3) or optik (same, but as downloadable library for older
pythons)? It's much nicer.

'as
Jul 18 '05 #3
Don Low wrote:
options, xarguments = getopt.getopt(sys.argv[1:], 'ha', \ [snip] When I execute the script with the -a option or the --view option as in:

./script_name -a myarg

It should report back:

-a = myarg


The second argument should have a colon after any letter/option that
takes an argument.
Also, a useful trick is to cast the opts to a dict. This prevents the
need for iterating over the opts and allows for concise definition of
default arguments.

e.g.
opts,args = getopt.getopt(sys.argv[1:] , 'h:a:v' )
opts = dict(opts)

hparm = opts.get('-h','cutie')
aparm = float( opts.get( '-a', math.pi ) )
verbose = opts.has_key('-v')
Caveats: the dict trick does not allow an option to be specified more
than once (e.g. -vv), it also loses ordering.
- Mark

Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: David Bear | last post by:
I'm stumped. Trying to follow the docs and .. failure. here's the args >>> args '-Middwb@mainex1.asu.edu -AKHAAM@prlinux+898 -CA --D2003-08-20-09:28:13.417 -Ff -Hprlinux...
4
by: Dan Rawson | last post by:
Is there any way to force getopt to process one option first?? I'd like to be able to pass in the name of a configuration file for my application, then have the remaining command-line parameters...
3
by: Dominik Kaspar | last post by:
I tried to use getopt and copied the example from: http://www.python.org/doc/current/lib/module-getopt.html but nothing is working... getopt.GetoptError doesn't seem to exist and when i run the...
6
by: Frans Englich | last post by:
Hello, In my use of getopt.getopt, I would like to make a certain parameter mandatory. I know how to specify such that a parameter must have a value if it's specified, but I also want to make...
1
by: Andrew | last post by:
Dear Experts, I have a perl program that using Getopt:Std module, when I try to run the GetOpt program, the following error returned: Can’t locate Getopt.pm in @INC (@INC contains:...
14
by: José de Paula | last post by:
Is getopt() and its companions, commonly found in GNU libc and other Unices libc, part of the C standard? Another doubt: I have a switch inside a while loop; is there a way to break out of the...
4
by: pinkfloydhomer | last post by:
I want to be able to do something like: myscript.py * -o outputfile and then have the shell expand the * as usual, perhaps to hundreds of filenames. But as far as I can see, getopt can only...
1
by: Daniel Mark | last post by:
Hello all: I am using getopt package in Python and found a problem that I can not figure out an easy to do . // Correct input D:\>python AddArrowOnImage.py --imageDir=c:/ // Incorrect...
2
by: auditory | last post by:
I have sources written on linux quite long ago. They are compiled good on current linux machine. but not in VS2005. The cause of problem is #include<getopt.h>. Is there any correspoinding...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.