473,887 Members | 2,309 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 2318

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
2793
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
2329
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
7041
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
3701
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
1513
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
2135
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
1146
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
9604
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
2898
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
9957
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
11173
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
10877
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
10434
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 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...
0
9593
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7988
isladogs
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...
0
5810
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...
1
4633
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
3
3245
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.