473,621 Members | 2,743 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to handle wrong input in getopt package in Python?

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
Traceback (most recent call last):
File "AddArrowOnImag e.py", line 113, in ?
File "AddArrowOnImag e.py", line 88, in main
File "getopt.pyc ", line 89, in getopt
File "getopt.pyc ", line 157, in do_longs
getopt.GetoptEr ror: option --imageDir requires argument

Is there any method in getopt or Python that I could easily check the
validity of each
command line input parameter?

Thank you
-Daniel
FYI: My code that deals with getopt is as follows:

o, a = getopt.getopt(s ys.argv[1:], 'h', ['imageDir='])

opts = {}
for k,v in o:
if k in ['--imageDir'] and len(v) == 0:
usage(); sys.exit("Insuf ficient input parameters!")
opts[k] = v
if opts.has_key('-h'):

usage(); sys.exit(0)
if not len(opts['--imageDir']):
usage(); sys.exit("Insuf ficient input parameters!")

Aug 25 '06 #1
1 2304

Danielgetopt.Ge toptError: option --imageDir requires argument

Which is precisely what the getopt module should do.

DanielIs there any method in getopt or Python that I could easily
Danielcheck the validity of each command line input parameter?

Getopt already did the validity check for you. Just catch its exception,
display a meaningful usage message, then exit, e.g.:

try:
o, a = getopt.getopt(s ys.argv[1:], 'h', ['imageDir='])
except getopt.GetoptEr ror, msg:
usage(msg)
raise SystemExit # or something similar

My usual definition of usage() looks something like this:

def usage(msg=""):
if msg:
print >>sys.stderr, msg
print >>sys.stderr
print >sys.stderr, __doc__.strip()

This will display the module-level doc string for the user. I find that a
convenient place to document the usage of scripts. For more complex
programs where command line arg processing is in a separate module you may
have to do something like:

def usage(msg=""):
if msg:
print >>sys.stderr, msg
print >>sys.stderr
import __main__
print >sys.stderr, __main__.__doc_ _.strip()

Skip
Aug 25 '06 #2

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

Similar topics

6
2782
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...
3
2313
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
3
7023
by: Don Low | last post by:
Hi, I'm going over a script that demonstrates the getopt function. I include the script here: #! /usr/bin/python import sys, getopt, string
6
3692
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):
9
1500
by: killermookie | last post by:
I'm not a javascripter so this is slightly unfamiliar to me. What I'm trying to do is that if someone clicks the radio button for Other, then the text input for other will become enabled. What is wrong with this? Thank you! <html> <head> <script language="JavaScript"> <!--
4
2124
by: Wally | last post by:
int main(int argc, char *argv) { int c; int port=0; char *srvname = NULL; extern char *optarg; /* **Determine whether we are converting a port **number to a server name or vice versa. */
3
1135
by: KLEIN Stéphane | last post by:
Hi, I would like print tabular values on terminal (stdout). Are there package to handle table text render ? Thanks for your help, Stephane
4
9585
by: prashant | last post by:
I am running a python script which has the line import getopt, sys, os, re, string And i get the error ImportError: No module named getopt Could you please point out a possible solution for this?
8
2885
by: dmoore | last post by:
Hi folks, I've seen the following issue come up in multiple posts to this mailing list: I have a python program that spawns a child process with popen or popen2 or popen3 or popen2.popen2 etc. the child process is interactive: it asks for input then spits out some output, asks for more input then spits out some output. for example, consider the trivial child program:
0
8213
marktang
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...
0
8156
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,...
0
8653
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8306
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
5554
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4150
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2587
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
1
1763
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1460
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.