problem with Python class creating


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

Posted On: Monday 5th of November 2012 02:15:30 AM Total Views:  237
View Complete with Replies

RELATED TOPICS OF Python Programming PROGRAMMING LANGUAGE




StringIO MySQL data blob Image problem

I am trying to insert an image, which is stored as a blob in MySQL, into a table using Reportlab. I have tried this: from StringIO import StringIO cfoto = StringIO(result[0][1]) # where result[0][1] is the 'blob' cfoto.seek(0) foto=cfoto.getvalue But when I do: print foto, I see something similar to this: array('c','\xff\xd8\............etc.......etc......') This is also the string I see in the table, in stead of the actual image. I have tried: cfoto StringIO() cfoto.write(result[0][1].tostring()) foto=cfoto.getvalue() that returns: \t\tlboq5\t\\t\t\tY|A\t,\t\t"\tm3Z\tf\t""N,\t\tI\tt"b5@xq'k\ts\td\t\t\t1\t ^J*C(r){:t_\t\tjo\t C(c)\t[)gN\tXi etc... etc... and return an UnicodeDecodeError when I try to insert this into the table Any ideas or clues someone Your help is appreciated. Dimitri (BTW, the MySQL image blob is valid, it shows up in MySQL Query Browser) -- --- You can't have everything. Where would you put it -- Steven Wright --- please visit www.serpia.org
VIEWS ON THIS POST

105

Posted on:

Monday 5th November 2012
View Replies!

problems using pythom tempfile module

, I'm trying to test the tempfile module with the following script, which basically creates a temporary file, fills the file with some test data and prints it. import tempfile t = tempfile.TemporaryFile() t.write("lalalala") t.flush() print t.read() Unfortunately, the print statement gives me an empty string. Can somebody tell me what I'm doing wrong regards Samir
VIEWS ON THIS POST

123

Posted on:

Monday 5th November 2012
View Replies!

RE: win32com problem: more than one instance

Thomas, excel registers its COM objects with REGCLS_SINGLEUSE that means one COM object is created per process. In Solidworks it seems that that they register with REGCLS_MULTIPLEUSE, which means on process can serve more than one COM object. Hence you have no chance to get multiple instances running in any COM client. Stefan > -----Original Message----- > From: python-list-bounces+sschukat=dspace.de@python.org > [mailtoython-list-bounces+sschukat=dspace.de@python.org] On > Behalf Of Tim Golden > Sent: Friday, August 31, 2007 1:36 PM > To: Thomas Rademacher > Cc: python-list@python.org > Subject: Re: win32com problem: more than one instance > > Thomas Rademacher wrote: > > , > > > > I start my script convert.py 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 *think* -- and I'm really hoping someone more knowledgeable > can chip in here -- that it's down to the particular COM > object implementation. ie Excel may choose to offer you > separate instances (or whatever they're called) while > SolidWorks may not. > > TJG > -- > http://mail.python.org/mailman/listinfo/python-list >
VIEWS ON THIS POST

149

Posted on:

Monday 5th November 2012
View Replies!

encoding problems

I would like to transform reST contents to HTML, but got problems with accented chars. Here's a rather simplified version using SVN Docutils 0.5: %------------------------------------------------------------- #!/usr/bin/env python # -*- coding: utf-8 -*- from docutils.core import publish_parts class Post(object): def __init__(self, title='', content=''): self.title = title self.content = content def _get_html_content(self): return publish_parts(self.content, writer_name="html")["html_body"] html_content = property(_get_html_content) # Instanciate 2 Post objects p1 = Post() p1.title = "First post without accented chars" p1.content = """This is the first. ....blabla .... end of post...""" p2 = Post() p2.title = "Second post with accented chars" p2.content = """Ce poste possde des accents : """ for post in [p1,p2]: print post.title, "\n" +"-"*30 print post.html_content %------------------------------------------------------------- The output gives me : First post without accented chars ------------------------------ This is the first. ....blabla .... end of post... Second post with accented chars ------------------------------ Traceback (most recent call last): File "C:\Documents and Settings\kib\Bureau\Projets\python\dbTest\rest_error.py", line 30, in print post.html_content UnicodeEncodeError: 'ascii' codec can't encode character u'\xe8' in position 39: ordinal not in range(128) Any idea of what I've missed
VIEWS ON THIS POST

141

Posted on:

Monday 5th November 2012
View Replies!

Re: Regular Expressions: Can't quite figure this problem out

Robert Dailey wrote: > > > On 9/24/07, *Gabriel Genellina* > wrote: > > Yes: forget about regular expressions. ElementTree does that for free: > > > That's not an option. > Even though it's built into Python 2.5 That's a strange requirement. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Sorry, the dog ate my .sigline
VIEWS ON THIS POST

150

Posted on:

Monday 5th November 2012
View Replies!

Threading problem when many sockets open

In message , Philip Zigoris wrote: > ... and the server > would go into a state where the master thread repeatedly polled the > socket and printed an error. Is that because it cannot create a new socket to accept the connection on
VIEWS ON THIS POST

160

Posted on:

Monday 5th November 2012
View Replies!

python 2.5 problems

Finally deleted 2.2 and loaded 2.5 (see below), using the msi, on my XP partition. Having intermittent system crashes. Assumed a corrupt download, so deleted and did another download/install. Same problems. The associated DLLs when XP says that it must shut down the idle shell are not consistent. So is there something not stable about ver 2.5 on XP Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
VIEWS ON THIS POST

203

Posted on:

Monday 5th November 2012
View Replies!

Mac OSX sqlite problem. Missing?

I've installed Mac Python 2.5. I'm running Mac OS X 10.4.10 on a Macbook 1.83GHz. I though that the python sqlite library was installed by default as part of Mac Python 2.5, however, I still have a problem. Sqlite does not appear to be my system: >>> import sqlite Traceback (most recent call last): File "", line 1, in ImportError: No module named sqlite I ran 'sudo easy_install pysqlite' which gave me the file 'pysqlite-2.3.5-py2.5-macosx-10.3-fat.egg', but no working pysqlite. I then downloaded the source files and ran 'python ez_setup.py pysqlite==2.3.5', which told me 'Using /Library/Frameworks/ Python.framework/Versions/2.5/lib/python2.5/site-packages/ pysqlite-2.3.5-py2.5-macosx-10.3-fat.egg' Still no working version of pysqlite. Tried installing from source. No problems appeared, but I still can't use pysqlite. The reason I am trying to install pysqlite, is to use turbogears, which initially failed when I ran 'tg-admin sql create', it failed with 'import sqlite. ImportError: No module named sqlite'. Any ideas gratefully received.
VIEWS ON THIS POST

108

Posted on:

Monday 5th November 2012
View Replies!

Re: StringIO MySQL data blob Image problem

ah, sorry a+=1 should be after 'Do stuff here' of course... On 9/5/07, 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. > > On 9/5/07, dimitri pater wrote: > > ---------- Forwarded message ---------- > > From: dimitri pater > > Date: Sep 5, 2007 9:13 PM > > Subject: Re: StringIO MySQL data blob Image problem > > To: Tim Golden > > > > > > > Well, I'm mystified. Not by your results: that exactly what I > > > expected to get, but because you're doing everything *except* > > > manipulating an image and putting it into a PDF via ReportLab. > > > > > Dear Tim, > > you are right of course, I have been trying to put the StringIO in a temp file: > > cfoto=StringIO > > cfoto.write(result[0][1].tostring()) > > dfoto=cfoto.getvalue() > > fileFoto=open('temp.jpg','wb') > > fileFoto.write(dfoto) > > > > and indeed, the blob from MySQL is saved as an image! > > however, > > foto= Image('temp.jpg') > > and inserting foto into a table results in: > > x = struct.unpack('B', image.read(1)) > > error: unpack str size does not match format > > oh, well... still needs some work > > BTW: I used 'local' images before (I mean they did not originate from > > a DB), that worked well in Reportlab's tables. > >
VIEWS ON THIS POST

95

Posted on:

Monday 5th November 2012
View Replies!

[win32] spawn background process and detach it w/o problems

! How to write portable (win32, unix) script that launches another program and continues its execution I've looked at spawn*() but it doesn't look in PATH dirs on windows so it's totally unusable when you don't know where exactly program is. I've looked at fork() way but there's no fork for windows. My current solution is thread.start_new(os.system, (
VIEWS ON THIS POST

216

Posted on:

Monday 5th November 2012
View Replies!

Pylons, SQLAlchemy, too many connections problem.

. I have pylons 0.96 (SVN) and current SQLAlchemy (0.3.10), and I have bug that doesn't exist earlier. My connection code: import sqlalchemy.mods.threadlocal from sqlalchemy import DynamicMetaData, objectstore metadata = DynamicMetaData( case_sensitive = False ) def db_connect( dsn ): engine = create_engine( dsn, echo=False, echo_pool=False, encoding='latin2', convert_unicode=True ) metadata.connect( engine ) command "netstat -an|grep 5432|grep ESTABLISHED|wc -l" displays one more connection after each refresh of page until I have exceptions such as: sqlalchemy.exceptions.DBAPIError: (Connection failed) (OperationalError) FATAL: sorry, too many clients already What is wrong
VIEWS ON THIS POST

126

Posted on:

Monday 5th November 2012
View Replies!

some problems with mod_python

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/mptest.py > 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.
VIEWS ON THIS POST

223

Posted on:

Monday 5th November 2012
View Replies!

Eclipse3.3 with Pydev 1.3.10 Mylar problem, have Mylyn

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
VIEWS ON THIS POST

172

Posted on:

Monday 5th November 2012
View Replies!

Re: StringIO MySQL data blob Image problem

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
VIEWS ON THIS POST

162

Posted on:

Monday 5th November 2012
View Replies!

win32com problem: more than one instance

, I start my script convert.py 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 (test_excel.py) 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
VIEWS ON THIS POST

264

Posted on:

Monday 5th November 2012
View Replies!

Code design problem

, 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
VIEWS ON THIS POST

136

Posted on:

Monday 5th November 2012
View Replies!

insert string problems..

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
VIEWS ON THIS POST

180

Posted on:

Monday 5th November 2012
View Replies!

A problem with Time

, 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
VIEWS ON THIS POST

160

Posted on:

Monday 5th November 2012
View Replies!

Socket communication problem

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
VIEWS ON THIS POST

146

Posted on:

Monday 5th November 2012
View Replies!

Using arrays in Python - problems.

, ! 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.
VIEWS ON THIS POST

238

Posted on:

Monday 5th November 2012
View Replies!