473,722 Members | 2,468 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Option parser question - reading options from file as well as commandline

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.

Doing a test print of options.qmanage r shows it unassigned.

Any ideas?

#
# Parse command line options and automatically build help/usage
# display
#
if len(sys.argv) == 2:
infile= open(sys.argv[1],"rb").read( )
print infile
parser=OptionPa rser( infile )
else:
parser = OptionParser()

parser.add_opti on("-m","--qmanager", dest="qmanager" ,
help="\t\tQueue Manager to inquire against"),
parser.add_opti on("-q","--queue", dest="queue",
help="\t\tQueue the message will be sent to"),
parser.add_opti on("-t","--to", dest="mto",
help="\t\taddre ss any mail messages will be sent to")
(options, args) = parser.parse_ar gs()

print options.qmanage r
May 16 '06 #1
8 3513
Andrew Robert <an************ @gmail.com> wrote in
news:12******** *****@corp.supe rnews.com:
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.

Doing a test print of options.qmanage r shows it unassigned.

Any ideas?


Check parser.usage, it is likely to look a lot like your infile.

I'm not sure, but I think you need to pass your alternative arguments
to parser.parse_ar gs.

max

May 16 '06 #2
Max Erickson wrote:
Andrew Robert <an************ @gmail.com> wrote in
news:12******** *****@corp.supe rnews.com:

<snip>

<\snip> Check parser.usage, it is likely to look a lot like your infile.

I'm not sure, but I think you need to pass your alternative arguments
to parser.parse_ar gs.

max

Hi Max,

I tried passing in the read line like so:

infile= open(sys.argv[1],"rb").read( )
parser=OptionPa rser()
print infile
(options, args) = parser.parse_ar gs(infile)

I end up getting the following traceback.

Traceback (most recent call last):
File "C:\Documen ts and Settings\Andrew Robert\My
Documents\recei ver.py", line 327, in ?
(options, args) = parser.parse_ar gs(infile)
File "C:\Python24\li b\optparse.py", line 1275, in parse_args
stop = self._process_a rgs(largs, rargs, values)
File "C:\Python24\li b\optparse.py", line 1322, in _process_args
del rargs[0]
TypeError: object doesn't support item deletion

Any ideas?
May 16 '06 #3
Andrew Robert <an************ @gmail.com> wrote in
news:12******** *****@corp.supe rnews.com:
Any ideas?


I don't know much about optparse, but since I was bored:
help(o.parse_ar gs) Help on method parse_args in module optparse:

parse_args(self , args=None, values=None) method of
optparse.Option Parser instance
parse_args(args : [string] = sys.argv[1:],
values : Values = None)
-> (values : Values, args : [string])

Parse the command-line options found in 'args' (default:
sys.argv[1:]). Any errors result in a call to 'error()', which
by default prints the usage message to stderr and calls
sys.exit() with an error message. On success returns a pair
(values, args) where 'values' is an Values instance (with all
your option values) and 'args' is the list of arguments left
over after parsing options.
o.parse_args('s even') Traceback (most recent call last):
File "<pyshell#1 5>", line 1, in ?
o.parse_args('s even')
File "C:\bin\Python2 4\lib\optparse. py", line 1275, in parse_args
stop = self._process_a rgs(largs, rargs, values)
File "C:\bin\Python2 4\lib\optparse. py", line 1322, in _process_args
del rargs[0]
TypeError: object doesn't support item deletion


That's the result of poking an optionParser instance in Idle.
parse_args is expecting something that looks like sys.argv[1:], which
is a list. You are passing it a string.

max

May 16 '06 #4
Max Erickson wrote:
I don't know much about optparse, but since I was bored:
help(o.parse_ar gs) Help on method parse_args in module optparse:

parse_args(self , args=None, values=None) method of
optparse.Option Parser instance
parse_args(args : [string] = sys.argv[1:],
values : Values = None)
-> (values : Values, args : [string])

Parse the command-line options found in 'args' (default:
sys.argv[1:]). Any errors result in a call to 'error()', which
by default prints the usage message to stderr and calls
sys.exit() with an error message. On success returns a pair
(values, args) where 'values' is an Values instance (with all
your option values) and 'args' is the list of arguments left
over after parsing options.
o.parse_args('s even')

Traceback (most recent call last):
File "<pyshell#1 5>", line 1, in ?
o.parse_args('s even')
File "C:\bin\Python2 4\lib\optparse. py", line 1275, in parse_args
stop = self._process_a rgs(largs, rargs, values)
File "C:\bin\Python2 4\lib\optparse. py", line 1322, in _process_args
del rargs[0]
TypeError: object doesn't support item deletion

That's the result of poking an optionParser instance in Idle.
parse_args is expecting something that looks like sys.argv[1:], which
is a list. You are passing it a string.

max

Yup.. the code now works as:

parser = OptionParser()

if len(sys.argv) == 2:
lines = open(sys.argv[1],"rb").readline s()
for line in lines:
line=line.strip ()
if not line:
continue
short, long, dest, help, default = line.split(";")
help = "\t\t" + help # Prepend tabs to help message
parser.add_opti on(short, long, dest=dest, help=help, default=default )
else:
parser.add_opti on("-m","--qmanager", dest="qmanager" ,
help="\t\tQueue Manager to inquire against"),
parser.add_opti on("-q","--queue", dest="queue",
help="\t\tQueue the message will be sent to"),
parser.add_opti on("-d","--dest", dest="dest",
help="\t\tDesti nation File Name"),
parser.add_opti on("-f", "--file",
action="store", type="string", dest="filename" ,
help="File to be transmitted", metavar="FILE")

(options, args) = parser.parse_ar gs()
thanks all for the insight
May 16 '06 #5

Andrew Robert wrote:
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.


After reading your post I decided to play around with optparse a bit,
to get acquainted with it.

Experimenting with IDLE I found that the Values object returned by
parse_args has a method 'readfile', and this 'readfile' method allows
you to add options to the Values object.

The syntax should be in the form:

<option>=<value >

<option> should not include the hyphens -- if your option is added as
'-x', then you should write:

x=3

not:

-x=3

If you have options with both long names and short names, then you
should use the long name -- if your option is added as '-f', '--file',
then you should write:

file=foo.txt

not:

f=foo.txt
Also, you need the assignment-operator in your file.

I didn't find any documentation on this, and I didn't try this with any
actions; only with options added to the parser like
op.add_option('-x', dest='x')

Using this 2-step approach allows you to use optparse itself to get to
the command-line option with your command-line settings...
Out of pure personal interest, what queuing-system are you writing to
from Python? What libraries do you have for that? And is it commercial
software, or freely downloadable?
(I'd love to be able to write messages to IBM MQ Series from Python)

Cheers,

--Tim

May 17 '06 #6
Tim N. van der Leeuw wrote:
Andrew Robert wrote:
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.


After reading your post I decided to play around with optparse a bit,
to get acquainted with it.

Experimenting with IDLE I found that the Values object returned by
parse_args has a method 'readfile', and this 'readfile' method allows
you to add options to the Values object.

The syntax should be in the form:

<option>=<value >

<option> should not include the hyphens -- if your option is added as
'-x', then you should write:

x=3

not:

-x=3

If you have options with both long names and short names, then you
should use the long name -- if your option is added as '-f', '--file',
then you should write:

file=foo.txt

not:

f=foo.txt
Also, you need the assignment-operator in your file.

I didn't find any documentation on this, and I didn't try this with any
actions; only with options added to the parser like
op.add_option('-x', dest='x')

Using this 2-step approach allows you to use optparse itself to get to
the command-line option with your command-line settings...
Out of pure personal interest, what queuing-system are you writing to
from Python? What libraries do you have for that? And is it commercial
software, or freely downloadable?
(I'd love to be able to write messages to IBM MQ Series from Python)

Cheers,

--Tim

Hi Tim,

I am using the pymqi module which is freely available at
http://pymqi.sourceforge.net/ .

Documentation on the module can be found at
http://pymqi.sourceforge.net/pymqidoc.html .

I have a few python examples on my web site located at
http://home.townisp.com/~arobert/

There are also a lot of good examples at
http://www.koders.com/info.aspx?c=Pr...5ZH7GC9AX54PAC
..

If you come up with anything, I would be glad to see what you have.
Back to the original issue:

I'm not sure exactly what you mean about the readfile option and format.

Could you send me a code snippet so I can get a better feel for it?
Thanks,
Andy
May 17 '06 #7

Andrew Robert wrote:
Tim N. van der Leeuw wrote:
Andrew Robert wrote: [...]
Hi Tim,

I am using the pymqi module which is freely available at
http://pymqi.sourceforge.net/ .

Documentation on the module can be found at
http://pymqi.sourceforge.net/pymqidoc.html .

I have a few python examples on my web site located at
http://home.townisp.com/~arobert/

There are also a lot of good examples at
http://www.koders.com/info.aspx?c=Pr...5ZH7GC9AX54PAC
.

If you come up with anything, I would be glad to see what you have.


Thanks a lot for these examples! I have some Java tools that send MQ
messages (reading, in fact, a ton of command-line arguments from a
file) and I need better tools. If I could use some Python for rewriting
this, it might speed me up a lot.

Back to the original issue:

I'm not sure exactly what you mean about the readfile option and format.

Could you send me a code snippet so I can get a better feel for it?
Thanks,
Andy


Here's the file I used:

===cut here===
x=4
w=6
what=7
zoo=9
===cut here===

Here's some snippets of code:
from optparse import OptionParser
op = OptionParser()
op.add_option('-x', dest='x')
op.add_option('--what', '-w', dest='what')
v=op.parse_args ()[0]
v.read_file('op tions-test.txt')
v

<Values at 0x12a9c88: {'x': 4, 'what': 7}>

As you can see, I'm parsing an empty command-line but I could parse a
full command-line as well before loading options from file.
After parsing the command-line, I get an instance of a 'Values' object,
and on this object I call a method 'read_file' with a filename. (I
could also call 'read_module', and it will add the __doc__ string).

I didn't test what happens with a more advanced useage of OptionParser
options.
Cheers,

--Tim

May 17 '06 #8
Andrew Robert wrote:
Hi Everyone.
I tried the following to get input into optionparser from either a file
or command line.


Hi Andrew,

I played around a bit more, not happy that the read_file method which I
discovered earlier on the Values - object takes a property-file like
input and doesn't call any callbacks (for instance).

So I wrote a little module to provide an option-parser callback for
reading arguments from file...

Since it seems that Google Groups doesn't allow me to attach the file,
I'll paste it into here, hoping that nobody objects very strongly:

=============== =============== =
"""Callback for optparse.Option Parser that interprets a command-line
argument as filename, reads the file, and adds the contents of the file
to the options to be parsed by the OptionParser.

Usage:
from args_from_file import add_argsfile_op tion
from optparse import OptionValueErro r
import sys
op = OptionParser()
add_argsfile_op tion(op, '-f', '--file')
op.parse_args(s ys.argv)


(This sample assumes that on the command-line, there is an option '-f'
or '--file'followed by the filename with options you wish to add to
the command-line).

The implementation reads the entire contents of the file into memory.

(c) Copyright 2006 Tim N. van der Leeuw (ti************ *@nl.unisys.com )
"""
import re
from optparse import OptionValueErro r

#SPLIT_ARGS = r'("[^"]*"|\'[^\']*\'|[^\s]+)'
SPLIT_ARGS = r'((?:")([^"]*)(?:")|(?:\')([^\']*)(?:\')|[^\s]+)'
g_split_args_re = None

def extract_args_fr om_string(arg_s tr, append_to=None) :
global g_split_args_re
if not g_split_args_re :
g_split_args_re = re.compile(SPLI T_ARGS)
argv = g_split_args_re .findall(arg_st r)
argv = ([v for v in x if v <> ''][-1] for x in argv)
if not append_to is None:
return append_to.exten d(argv)
else:
return list(argv)

def load_file(filen ame, skip_comments=T rue):
f = None
try:
f = open(filename, 'rb', 16384)
if skip_comments:
lines = "".join((li ne for line in f if line.strip()[0] <>
'#'))
else:
lines = "".join(f)
return lines
finally:
if f <> None:
f.close()

def optparse_cb_loa d_args_from_fil e(option, opt, value, parser):
try:
args = load_file(value )
extract_args_fr om_string(args, parser.rargs)
except Exception, e:
raise OptionValueErro r(
'Error parsing argument %s, with reading options from
option-file "%s". Originating error: %s' %
(opt, value, e))
return

def add_argsfile_op tion(parser, *option_names):
return parser.add_opti on(*option_name s,
**{'type':'stri ng',
'action':'callb ack',
'callback':optp arse_cb_load_ar gs_from_file})
=============== =============== =

Feel free to use as you like. Might make a nice addition to the
standard action types of optparse in the standard library? If there's
interest in that, I might try to write a patch for optparse.

Cheers,

--Tim

May 22 '06 #9

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

Similar topics

4
2295
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
4
4007
by: Sam Smith | last post by:
I am using optparse for the commandline parsing for my programs. I was wondering if it is possible to detect if an option or option-arg has been specified on the commandline by the user or not. Please do not suggest default value solutions. Thanks.
9
2206
by: Ritesh Raj Sarraf | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I'm using optparse module to parse all options and arguments. My program uses mostly "option arguments" hence my len(args) value is always zero. I need to check if the user has passed the correct number of "option arguments". Something like:
4
1650
by: Mathias Waack | last post by:
We've integrated python into a legacy application. Everything works fine (of course because its python;). There's only one small problem: the application reads the commandline and consumes all arguments prefixed with a '-' sign. Thus its not possible to call a python module from the commandline with a parameter list containing options prefixed by '-' or '--' signs. Thats not a major problem, but it prevents us from using th optparse...
2
1822
by: Lucas Malor | last post by:
Hello all. I'm trying to do a little script. Simply I want to make a list of all options with them default values. If the option is not specified in the command line, the script must try to read it in a config.ini file. If it's not present also there, it must set the default value. The problem is I maked a simple list for this: optname = , , , But I must check that the option was specified in command line:
4
4577
by: Karthik Gurusamy | last post by:
Hi, I see that I can provide a default value for an option. But I couldn't find out any way if the user really entered the option or the option took that value because of default. A simple check for value with default may not always work as the user might have manually entered the same default value. Let's assume I want to take in the ip-address using -i <ip-addr>. If user didn't give it explicitly, I am going to use socket interface
28
16414
by: Marc Gravell | last post by:
In Linq, you can apparently get a meaningful body from and expression's .ToString(); random question - does anybody know if linq also includes a parser? It just seemed it might be a handy way to write a safe but easy implementation (i.e. no codedom) for an IBindingListView.Filter (by compiling to a Predicate<T>). Anybody know if this is possible at all? Marc
2
1335
by: chrisber | last post by:
using the unittest module in Python 2.3.5, I've written some test code that ends up with if __name__ == "__main__": unittest.main() Since I want to run this code in various environments, I'd initially added some commandline options, e.g. to specify a configuration file like so
1
2650
by: GustavoTabares | last post by:
Hello, I'm trying to figure out if the following is a bug or if I'm using the remove_option in the wrong way. #!/usr/bin/env python import optparse parser = optparse.OptionParser() parser.add_option("--test", help="This is a test option") parser.remove_option('--test')
0
8740
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
9386
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
9158
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
9090
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...
1
6685
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
4503
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...
0
4764
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2606
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2148
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.