473,738 Members | 9,555 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Parse command line options

hue
I am trying to parse command line options using getopt module.

I have written the following Code

import string

import getopt

def usage():
print '''haarp_make.p y -- uses getopt to recognize options

Options: -n -- No
-t -- Time
-h -- help
-i -- image_file
-o -- Output:filename '''

sys.exit(1)

def main():
try:

opts,args = getopt.getopt(s ys.argv[1:], 'n:t:h:i:o:',
["Number=","time =","help=","ima ge_file=","Outp ut Filename="])

except getopt.GetoptEr ror:
print 'Unrecognized argument or option'
usage()
sys.exit(0)

I have gone through getopt module from the help in python Library, but
i couldnot proceed from here.

My Task is

python MyScriptName.py n t h i o

How to parse those arguments, i is an Image File.
Please try to give some comments.
Hoping for a reply.

Jul 19 '05 #1
5 3452
Hue wrote:
try:

opts,args = getopt.getopt(s ys.argv[1:], 'n:t:h:i:o:',
["Number=","time =","help=","ima ge_file=","Outp ut Filename="])

except getopt.GetoptEr ror:
print 'Unrecognized argument or option'
usage()
sys.exit(0)


Proceed with e.g.:

#v+

for (opt, arg) in opts:
if opt in ('-n', '--No'):
do_no()
elif opt in ('-t', '--Time'):
do_time()
# [...]
else:
barf(opt, arg)
# end if
# end for

#v-

But be consistent when using long options: use all lowercase, use either
dashes or underscores (not both), don't use whitespace.

I usually do something like:

#v+

Options = {
'i:': 'input=',
'o:': 'output=',
'c' : 'copyright',
'h' : 'help',
'v' : 'version',
}
shortOpts = ''.join(Options .keys())
longOpts = Options.values( )

# [...]

try:
(opts, args) = getopt.getopt(a rgv[1:], shortOpts, longOpts)
except getopt.error, msg:
die(msg)
# end try

# [...]

for (opt, arg) in opts:
# Handle all options
:
# end for

#v-

Additional, non-option, arguments will be in the "args" variable.

Cheers,

--
Klaus Alexander Seistrup
Magnetic Ink, Copenhagen, Denmark
http://magnetic-ink.dk/
Jul 19 '05 #2
hue wrote:
<SNIP>
try:

opts,args = getopt.getopt(s ys.argv[1:], 'n:t:h:i:o:',


^^^^^^^
This may be the problem. As I recall, a colon following an option
indicates that it is followed by an argument as in "-f filename".
For options that are just switches (that take no argument), I believe
they should appear in the list above *without* the colon suffix...


--
----------------------------------------------------------------------------
Tim Daneliuk tu****@tundrawa re.com
PGP Key: http://www.tundraware.com/PGP/
Jul 19 '05 #3
Hue,
It looks like you may have options and arguments confused. Arguments
are the pieces of information that your program needs to run. Options
are used to tune the behaviour of your program.

For example:
grep -i foo bar
Tries to match the expression "foo" in the file "bar", ignoring the
case of the letters. The grep program needs to know what expression to
look for and where to look, so "foo" and "bar" are arguments. Ignoring
the case of the letters is tuning the behaviour of the grep program -
in this case making it less sensitive. The program will run without it.
If your task is :
python MyScriptName.py n t h i o
Then n, t, h, i and o are arguments. You can get them from the args
array:

import sys
print ",".join(sys.ar gv)

would print "n, t, h, i, o"

If you are using options, you must put dashes before them, and they
must be before the arguments. So, if this was hue.py:

import sys
import string
import getopt

def usage():
print '''haarp_make.p y -- uses getopt to recognize options

Options: -n -- No
-t -- Time
-h -- help
-i -- image_file
-o -- Output:filename '''

sys.exit(1)

def main():

print "SYS ARGV: ", ",".join(sys.ar gv)
try:

opts,args = getopt.getopt(s ys.argv[1:], 'n:t:h:i:o:',
["Number=","time =","help=","ima ge_file=","Outp ut Filename="])

except getopt.GetoptEr ror:
print 'Unrecognized argument or option'
usage()
sys.exit(0)

print "OPTS: ", ",".join([repr(o) for o in opts])
print "ARGS: ", ",".join(ar gs)

if __name__ == "__main__":
main()
Then:
C:\temp>python hue.py n t h i o
SYS ARGV: hue.py,n,t,h,i, o
OPTS:
ARGS: n,t,h,i,o

And:
C:\temp>python hue.py -i image.py n t h o
SYS ARGV: hue.py,-i,image.py,n,t, h,o
OPTS: ('-i', 'image.py')
ARGS: n,t,h,o

Hope that hepls.
Tom

Jul 19 '05 #4
hue
Thanks for your reply, I have used some of your ideas in my Code.

Jul 19 '05 #5
hue
Thanks for your reply, I have used some of your ideas in my Code.

Jul 19 '05 #6

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

Similar topics

4
2777
by: Edvard Majakari | last post by:
Hi, I was wondering what would be the most elegant way for creating a Python class wrapper for a command line utility, which takes three types of arguments: 1. options with values (--foo=bar) 2. boolean options (--squibble) 3. data lines (MUNGE:x:y:z:frob)
4
4059
by: rkoida | last post by:
Hello evryone I am a newbie to python. I have a makefile which i can compile in UNIX/LINUX, But i I am planning to write a python script which actually does what my MAKEFILE does. The make file is #Makefile and some scripts to give output #numbers #Change till sign #END
19
20583
by: linzhenhua1205 | last post by:
I want to parse a string like C program parse the command line into argc & argv. I hope don't use the array the allocate a fix memory first, and don't use the memory allocate function like malloc. who can give me some ideas? The following is my program, but it has some problem. I hope someone would correct it. //////////////////////////// //Test_ConvertArg.c ////////////////////////////
6
2198
by: Ian Davies | last post by:
Hello I have found the following script php/java for dynamic menu lists. Where a selection from the first updates (filters items in) the other. I have modified it for my tables. However I am getting an error Parse error: parse error, unexpected T_VAR in e:\domains\i\iddsoftware.co.uk\user\htdocs\QuestionDB\Questions.php on line 42
4
5004
by: Bit byte | last post by:
I have a project that I normally build (without problems) from the DevStudio IDE. However, I have embarked on automating all my builds (this test project being one of several). The project creates a DLL. I am able to build the project without any probs in the IDE, however - when I build the project from the command line (using the same options shown in the 'Command line' node in the 'Project Settings' dialog box), I get the following...
8
3514
by: Andrew Robert | last post by:
Hi Everyone. I tried the following to get input into optionparser from either a file or command line. The code below detects the passed file argument and prints the file contents but the individual swithces do not get passed to option parser.
3
10325
by: jlw16 | last post by:
Hello, I’m trying to use my vbs script to get a command line argument for a file which will need to be opened through QuickTestPro. Below are the commands I’m using: Dim qt_file 'As String -> If I don’t comment out the As String, I get an “Expected end of statement” error – is this correct?? qt_file = Command -> This doesn’t appear to be correct – when I echo out qt_file it’s null qtApp.Test.DataTable.Import qt_file ' Import data...
51
4144
by: Ojas | last post by:
Hi!, I just out of curiosity want to know how top detect the client side application under which the script is getting run. I mean to ask the how to know whether the script is running under Command Prompt or Browser or some other application? Ojas.
2
3226
by: Lawrence Krubner | last post by:
Imagine a template system that works by getting a file, as a string, and then putting it through eval(), something like this: $formAsString = $controller->command("readFileAndReturnString", $formName); // 06-22-07 - the next commands try to import all the functions that the
0
8969
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
8788
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
9335
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 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...
1
9263
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
8210
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...
0
6053
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
4570
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...
2
2745
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
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.