Problem with argument parsing

I have a python-script: myscript, used to start a program on another
computer and I use OptionParser in optpars.
I use it like this: myscript -H host arg1 -x -y zzz
I would like OptionParser to ignore all arguments after arg1, because
these are options that should be used by the program started on the
oter computer arg1 -x -y zzz.
One solution is to write: myscript -H host "arg1 -x -y zzz"
But is it in some way possible to instruct OptionParser to ignore -x -
y zzz without the "..."

Posted On: Monday 5th of November 2012 02:23:01 AM Total Views:  350
View Complete with Replies

Related Messages:

some problems with mod_python   (123 Views)
Johan a crit : > Hi > > I have installed and tested this on centos, fedora and freebsd all > give the same problem so I guess I missed some steps. > > I have compiled bot apache (2.2.4) and mod_python (3.3.1) according to > the docs and no problem with this. > But when I have made everything about testing mod_python an browse to > http://server/test and there expecting to see " world" I instead > get an index of contents in this directory. If I go to http://server/test/ > it works. No errors in any log either. > > What Have I missed The difference between AddHandler and SetHandler in apache's conf. > This I added to httpd.conf > > owOverride > AddHandler mod_python .py > PythonHandler mptest > PythonDebug On > Your problem is with Apache configuration, not with mod_python. The AddHandler directive maps /*.py to your handler. So you have to call .py to trigger the deed behaviour. If you want *any* url under to be handled by mptest, you need to use SetHandler, not AddHandler.
Eclipse3.3 with Pydev 1.3.10 Mylar problem, have Mylyn   (104 Views)
Right now I am trying to install pydev 1.3.10 on Eclipse 3.3. I am getting an Mylar error org.eclipse.mylar (2.0.0.v20070403-1300) or something needed. Mylyn is mylar, now. How do you disable the mylar dependency, so that Mylyn is used by PyDev
Re: StringIO MySQL data blob Image problem   (99 Views)
dimitri pater wrote: > > the following code works when inserting images in reportlab tables: > > (result4 is a query result) > a=0 > for i in result4: > cfoto = StringIO() > cfoto.write(result4[a][9].tostring()) > dfoto = cfoto.getvalue() > fileFoto = open(str(a)+'temp.jpg','wb') > fileFoto.write(dfoto) > fileFoto.close() > foto = Image(str(a)+'temp.jpg') > a+=1 > > Do stuff here (insert the Image) > > The problem with this code is that I need to create a unique file > (str(a)+'temp.jpg'), I tried to use a single temp.jpg but it kept > using the data from the first record. Tried flush(), truncate(0), but > it didn't work. (My mistake probably ;-) > But the images show in the PDF so that's fine for now. You've obviously already worked this one out, which is great. But if I might just comment on the code a little bit, in a spirit of helpful criticism: * It's not clear (to me) why you're using a StringIO at all. I'm not familiar with MySQL in particular, but in general, database interface modules will return a Python string or possibly a buffer object from a Blob field. In other words, is there anything to stop you simply writing "result4[a][9]" directly into a file # ... stuff leading up to: blob = result4[a][9] ofile = open ("temp.jpg", "wb") ofile.write (blob) # (or, possibly, str (blob) if it's a buffer) ofile.close () * Assuming you're using any recent version of Python, you can save the extra counter by iterating over enumerate (result4) which return a 0-based index and the indexed item as a tuple. In fact, now I look at it, you're doing the work twice. You're iterating over result4 but doing nothing with the "i" which is the result of the iteration. You might do better with something like this: # # I've used "a", "i" to match your code, # but more descriptive names are good, such # as n_result, result or whatever fits your mind. # for a, i in enumerate (result4): blob = i[9] ofile = open ("%d-temp.jpg" % a, "wb") ofile.write (blob) ofile.close () * Finally, the tempfile module is a good one to use for temporary files. (Although the xx-temp.jpg solution you used may be perfectly acceptable for your needs). In the above, I've avoided quite a few good-practice issues, such as try-except blocks when writing a file, or with-blocks in Python 2.5+. The code I've sketched out is merely a rough-and-ready illustration of a particular point, not a manual of best practice. I suspect you may be newish to Python, if not to programming in general. My comments above aren't intended to be nitpicks to show up your ignorance, but hopefully hints which might help you look at alternatives or consider alternative idioms within Python itself. Good luck with the PDFs! TJG
win32com problem: more than one instance   (136 Views)
, I start my script simultaneously in any dos-shells several times. But I get every time the same solidworks instance. I see in the proccess (task) manager only one solidworks.exe Therefore I get for all simultaneous conversions the same output file. I tested the same code with excel ( and her I get many instances of excel in proccess (task) manager. How can I get many instances of solidworks Is it a problem of python Or is it a problem of the Solidworks-COM-Implemention and I get the same problem with an C++ client implementation
Code design problem   (82 Views)
, I have a hard time figuring out an elegant and efficient design for the following problem. I am working on automation of structural design problems. In the majority of cases, this boils down to executing programs in batch in one or more loops. The scripts to control the execution differ from fortran to bash to python and so on. Most of them are ad hoc and what I call 'throw away scripts'. In order to improve the situation I would like to develop a Python module that supports the execution of external programs. Ideally I would like to make running locally or remote trivial for the users of the module. As an example, I would like the following (pseudo)-code to work: app = Application('patran') # Run on local machine app.start(args) app = Application('patran', host='myhost') # Run on remote machine app.start(args) The problem I face is that the implementation of the application class is completely different for the local and remote case. The local case is a straightforward implemenation using the subprocess module, the remote case is a CORBA implementation. Somehow I would like to switch from implementation class at runtime depending on whether or not the host parameter is specified or not. The Application, local implementation and remote implementation all have the same interface, so a possibility might be something like the following: class Interface(object): ..... def start(self): pass def stop(self): pass class LocalImplementation(Interface): ..... class GlobalImplementation(CorbaGlobalImplementation, Interface): ..... class Application(Interface): def __init__(self, program, host=None): .... if host: self.__impl = LocalImplementation(program) else: self.__impl = GlobalImplementation(program, host) # Forward all methods to the implementation class def start(self): self.__impl.start() def stop(self): self.__impl.stop() To me forwarding each call in the Application class looks a little bit redundant and I would like to get rid of it. Does anyone have any comments or suggestions Can metaclass programming come to rescue Kind regards, Marco Nawijn , Marco Nawijn writes: > The problem I face is that the implementation of the application class > is completely different for the local and remote case. The local case > is a straightforward implemenation using the subprocess module, the > remote case is a CORBA implementation. Somehow I would like to switch > from implementation class at runtime depending on whether or not the > host parameter is specified or not. > > The Application, local implementation and remote implementation all > have the same interface, so a possibility might be something like the > following: > To me forwarding each call in the Application class looks a little bit > redundant and I would like to get rid of it. Does anyone have any > comments or suggestions Can metaclass programming come to rescue It sounds like you could probably get away with just a factory function: def Application(program, host=None): if host is None: return LocalApplication(program) else: return RemoteApplication(program, host) Then just implement the same interface and/or derive from a common base class for LocalApplication and RemoteApplication. HTH!, -Marshall
insert string problems..   (102 Views)
Hi.. I want to insert some data to postgresql.. My insert code: yer="019" cursor.execute("INSERT INTO ids_%s (id) VALUES (%s)", (yer, id)) I don't want to use % when the insert operation. in this code give me this error: psycopg2.ProgrammingError: syntax error at or near "'019'" LINE 1: SELECT link_id from linkkeywords_'019' if i do int(yer) , 019 change to 19 .. How can i do int yer string with 0
A problem with Time   (104 Views)
, I need to return the date yesterday in the form DDMMYYYY. I looked through the modules: time, datetime and calendar but can't find anything that leaps out at me. The problem I'm having is that although I can use time.localtime and get a tuple of the year, month, day and so forth, I don't believe I can just minus 1 from the day, because I don't think it's cyclic, also, I can't see the date being linked in with the month. So is there any way of getting yesterdays date Thank You Dominic
Socket communication problem   (91 Views)
Sandy Dunlop wrote: > > I'm new here, and fairly new to Python. I have been playing around with > Python and started having a look at socket IO. I have written a script > that communicates over a network to a server which is written in C. > While trying to get this working, I have been running into a problem > where the Python client appears to hang when it should be receiving data > back from the server. I forgot to add, I'm using Python 2.5.1 on OS X, and have also tried my program under Python 2.5.1 on Solaris 9. Cheers, Sandy
Using arrays in Python - problems.   (122 Views)
, ! I've just started to use Python and its a lovely language! I've previously programmed in Fortran 95 and have just began to use numpy. I'm having a few problems with arrays in Python though and wondered if someone could offer me some advice I wrote the following Fortran code to randomly generate numbers from a log-normal distribution for use in a Monte Carlo model: do n=1,shotcount F(n)=G05DEF(F_mean,F_sd) enddo The array F(n) is dynamically allocated earlier on and is sized with reference to shotcount, the number of iterations the model performs. The problem is I can't get something like this to run in Python using numpy, and for the size of the array to be sized dynamically with reference to the variable shotcount. I acknowledge that my knowledge of Python is still really basic (I only started learning it a few days ago) and I'm trying to get out of the Fortran programming mindset but I'm stuck and don't seem to be able to get any further. If anyone could help I'd be really grateful.
problem with Python class creating   (121 Views)
Hi all, I have the code like this one: from myMisc import ooIter class MyClass: def __init__(self): pass iterfcn = lambda *args: ooIter(self) # i.e pass the class instance to other func named ooIter field2 = val2 field3 = val3 # etc So it yields "global name 'self' is not defined", that is true. How could I handle the situation Currently I do (and it works, but give me some troubles - I should call MyClass.__init__ for each children class, and there are lots of those ones) class MyClass: def __init__(self): iterfcn = lambda *args: ooIter(self) # i.e pass the class instance to other func named ooIter field2 = val2 field3 = val3 # etc I suspect it has better solution, is it Thank you in advance, Dmitrey
regexp problem in Python   (98 Views)
I want to find " Jadeed_Mlak14.wmvtsid=20070803-164051-9d637d11" or 3gp instead of wmv in the text file like this : ""some code"" function reportAbuse() { var windowname="abuse"; var url="/abuse.jsplink=" + " e2000f22/Jadeed_Mlak14.html"; OpenWindow =,windowname,'toolbar=no,scrollbars=no,resizable=no,width=500,height=500,left=50,top=50'); OpenWindow.focus(); } function startDownload(){ window.location = " e2000f22/Jadeed_Mlak14.wmvtsid=20070803-164051-9d637d11"; //document.downloadForm.submit(); } Jadeed_Mlak14.3gptsid=20070803-164051-9d637d11"sfgsfgsfgv I use this pattern : "http.*\.(wmv|3gp).*"" but it returns only 'wmv' and '3gp' instead of " download/1716611/e2000f22/Jadeed_Mlak14.wmv tsid=20070803-164051-9d637d11" what can I do what's wrong whit this pattern thanx for your comments
problems playing with dates from any month.   (102 Views)
hello, I have a very strange problem and I can't find any solution for that. I am working on an accounting package which I wish to develop in python. the simple problem is that I want to knoe how I can know if the given date is the nth day of a month. for example if a customer is supposed to pay his installment on every 5th of all months, I want to know if today is the fifth day (jan the fifth, feb the fifth etc) for any given month. I have not found any such function. if I have looked (or over looked ) in the wrong places I am really sorry. secondly I also want to know the way in which I can convert a given string to a date object. for example if I have a string "29/09/2005", I know it is a valid date although it is in a string form. now I want to convert the above string into a real date object. how can I cast it this way regards, Krishnakant.
Re: problems playing with dates from any month.   (103 Views)
krishnakant Mane wrote: > On 02/08/07, Ian Clark wrote: > >> >> > I looked there even before. > but could not figure out what the code did. > I know in that variable called s there was a string in a valid date format. > but when datetime.strptime was used, I did not understand the place > where a date object say d was created. > I would expect some thing like d = and the function. but I did not fine that. > only reference was the datetime module and the documentation is not as good. >>> import datetime >>> import time >>> fmt_string = '29/05/2005' >>> date_tuple = time.strptime(fmt_string, '%d/%m/%Y') >>> print date_tuple (2005, 5, 29, 0, 0, 0, 6, 149, -1) >>> date_tuple_minus_tz = date_tuple[0:6] >>> print date_tuple_minus_tz (2005, 5, 29, 0, 0, 0) >>> date_obj = datetime.datetime(*date_tuple_minus_tz) This last line is equivalent to the following: >>> date_obj = datetime.datetime(2005, 5, 29, 0, 0, 0) The * in front of a tuple expands it's arguments when making a function call >>> print date_obj 2005-05-29 00:00:0 >>> print == 5 False > another question I am getting is that where is the list of all > formatting characters. like for example Y is 4 digit year M is month > MM is month in 2 digits etc. > I am trying to locate a list of all these denoters. > can you provide me the place Look for the strptime() function. > > >> Then it's just: >> >> if == 5: >> print 'It's the fifth day of the month' >> > this was much better than the documentation,
Matplotlib axis control problem   (89 Views)
I would like to control the y axis of a plot. The following code does exactly what I want it to! On my linux computer it sets the y axis limits to 18.0 minimum, 58.0 maximum, plots some points on y=x, provides ticks at 20,30,40,50 and horizontal tick lines that intersect the plotted points. very good, but if I change the upper y axis limit to 54.0, (ax.set_ylim(18.0, 54.0)), it fails, plotting the ticks at some strange values. Ultimately I want to uncomment the set scale to log and use this to label semi log plots that by default are only labeled on powers of 10. My data falls within one decade so I don't want the full 10-100 limits. I'm rather new at matplotlib so if I'm making trivial errors please feel free to criticize.
Re: problem with change to exceptions   (143 Views)
En Fri, 27 Jul 2007 19:49:17 -0300, Neal Becker escribi: > import exceptions > > class nothing (exceptions.Exception): > def __init__ (self, args=None): > self.args = args > > if __name__ == "__main__": > raise nothing > > Traceback (most recent call last): > File "", line 1, in > File "/usr/tmp/python-3143hDH", line 5, in __init__ > self.args = args > TypeError: 'NoneType' object is not iterable > > I'll have to say, I don't understand this error. If this is all your code, try using just: class nothing(Exception): pass if __name__ == "__main__": raise nothing Exceptions are built-in since aeons ago, so you don't have to import the exceptions module. The standard Exception class has an "args" attribute, and it's expected to be a tuple (not None). See -- Gabriel Genellina
Strange problems with subprocess   (205 Views)
Hi all. I have a simple "ping tester" program that, every 1 minute (execute by linux crontab), create, with subprocess, a "ping -c 1 my_addrs". work, but sometime (about 1/2 times at a day), I receive this error message: File "/exports/srv-wipex/net_test/", line 88, in pyPing cmd_p = Popen(cmd, stdout=PIPE, stderr=PIPE) File "", line 543, in __init__ errread, errwrite) File "", line 970, in _execute_child data =, 1048576) # Exceptions limited to 1 MB What can be that raise this Python 2.4 in deb etch
Re: problem with change to exceptions   (115 Views)
Neal Becker wrote in news:f8e0g4$o1u$ > Alex Popescu wrote: > >> Neal Becker wrote in >> news:f8dspe$fm2$ >> > > [snip...] > >>> >> >> You can pass to the exception: >> a) a string (it will become the message) >> b) a tuple of values (can it be a list also) >> >> In your case there is no message, no values so args is NoneType. >> > Yes, args is None. So the assignment: > self.args = args > > should set self.args to None. Nothing wrong there, and what has this > got to do with NoneType being iterable > args are used to generate the traceback when a message was not provided. ../alex -- ..w( the_mindstorm )p.
Xinetd & python server script. problem to get data from from client   (160 Views)
I wrote simple script to test communication: When i connect via telnet like: "telnet localhost 51423" the server is working send and receive information. but when i connected to him via client scrip so client script receive messages from server but server doesn't receive message from client. In xinetd.conf and servers conf file "only_from =" already choosen. What can i do Here below are my client and server: Thank you Server: #!/usr/bin/env python # example import sys import os print "Wellcome" print "please enter the string" sys.stdout.flush() line = sys.stdin.readline().strip() print "You entered %d characters." % len(line) sys.stdout.flush() client: import sys import string import os import time import socket import popen2 PORT = 51423 HOST = ""#sys.argv[1] sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((HOST, PORT)) print "Connected from:", sock.getsockname() print "Connected to:",sock.getpeername() while 1: print "waiting" result = sock.recv(1024) print result sock.send('foo') print "Sent: foo" if result == 3: break
"struct" module problem w/ pyinstaller   (88 Views)
, I am trying to create exectuables on inux using "pyinstaller". I am using pyinstaller-1.3, RHEL 4.4, Python 2.5. The executables fail to run. The problem returned is pertaining to "" not being able to find the module "_struct". is located under /usr/local/lib/python-2.5/, and there is a _struct.o (no anywhere) located under /usr/local/lib/ python-2.5/lib-dynload. When trying to run the executable, the loader returns: File "/usr/local/lib/python2.5/", line 30, in ImportError: No module named _struct The line in question is: from _struct import Struct, error I am a python neophyte. If someone could give me some information, I would appreciate it.
pyparser and recursion problem   (100 Views)
On 2007-07-26, wrote: > Using pyparser, I'm trying to parse a string like this: > >:Start: first SECOND THIRD :SECOND: second1 | second2 :THIRD: third1 | > FOURTH :FOURTH: fourth1 | fourth2 > > I want the parser to do the following: > 1) Get the text for the :Start: label e.g ('first SECOND THIRD') > 2) Do nothing with the lower-case words e.g ('first') > 3) For each upper-case word find the corresponding entries, and > replace the word > with these entries (the '|' indicates separate records) > e.g. for 'SECOND', replace the word with ("second1", "second2") > 4 Do this recursively, because each item in '3' can have upper-case > words > > I can do this - but not within pyparser. I had to write a > recursive function to do it. I would like to do it within > pyparser however. pyparser is a great parser, but out of the box it only parses. To get it to convert a text file into a new form you'll have to write most of the conversion code yourself, and merely hook it into pyparser. The critical step you're missing (and that I missed until my third try) is the setParseAction method, with which you can monkey around with the resulting parse tree. On the other hand, since you got it working without pyparsing, probably you're problem doesn't need pyparsing. Hopefully I'll have time to help you a bit more later, or Paul MaGuire will swoop down in his pyparsing powered super-suit. -- Neil Cerutti , ,