473,322 Members | 1,425 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,322 software developers and data experts.

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.py -- 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(sys.argv[1:], 'n:t:h:i:o:',
["Number=","time=","help=","image_file=","Outpu t Filename="])

except getopt.GetoptError:
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 3434
Hue wrote:
try:

opts,args = getopt.getopt(sys.argv[1:], 'n:t:h:i:o:',
["Number=","time=","help=","image_file=","Outpu t Filename="])

except getopt.GetoptError:
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(argv[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(sys.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****@tundraware.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.argv)

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.py -- 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.argv)
try:

opts,args = getopt.getopt(sys.argv[1:], 'n:t:h:i:o:',
["Number=","time=","help=","image_file=","Outpu t Filename="])

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

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

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
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)...
4
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...
19
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....
6
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...
4
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...
8
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...
3
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 ->...
51
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...
2
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",...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.