473,834 Members | 1,840 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ



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'''

options, xarguments = getopt.getopt(s ys.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.'''

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

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

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

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

for a in options[:]:
if a[0] == '--version':
print 'options version 0.0.001'

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


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?


Jul 18 '05 #1
3 7036
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(s ys.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(s ys.argv[1:], 'ha:', \
['file=', 'view=', 'version', 'python-version'])
Jul 18 '05 #2
Don Low <m_*******@symp atico.ca> writes:

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.

Jul 18 '05 #3
Don Low wrote:
options, xarguments = getopt.getopt(s ys.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.

opts,args = getopt.getopt(s ys.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

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 --JTCPIP_NPF_TEST_DARS_PORTRAIT -NTCPIP_NPF_TEST_DARS_PORTRAIT --Pholdqueue -Qholdqueue -aacct -b2895 -d/var/spool/lpd/holdqueue -edfA898prlinux -fTCPIP_NPF_TEST_DARS_PORTRAIT -hprlinux -j898 -kcfA898prlinux -l66 -nKHAAM -sstatus -t2003-08-20-09:28:13.000 -w80 -x0 -y0...
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 over-ride the configuration file if they are present. For the moment, I'm restricted to 2.2 versions. TIA . . . . Dan
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 program commenting this out, none of "-v", "-h" and "-o" wants to be recognized... what's the matter?! Dominik
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 the parameter itself mandatory(combined with a mandatory value, the result is that the user must specify a value). Here's code illustrating my point(see the TODO):
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: /opt/perl5/lib/5.00502/PA-RISC1.1 /opt/perl5/lib/5.00502 /opt/perl5/lib/site_perl/5.005/PA-RISC1.1 /opt/perl5 I am using Perl 5.6.1 in HPUX 11. Any hints?
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 loop from the switch without using goto? I mean: start: while(chr = fgetc(inputfile)) { switch(chr)
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 get one argument with each option. In the above case, there isn't even an option string before the *, but even if there was, I don't know how to get getopt to give me all the expanded filenames in an option.
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 input D:\>python AddArrowOnImage.py --imageDi
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 files which can be used instead of getopt.h?? I tried xgetopt.h from codeproject http://www.codeproject.com/cpp/xgetopt.asp
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Duprť who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.