Re: Python compiled on Windows
On Mon, 05 Feb 2007 12:17:48 +0100, hg <[EMAIL PROTECTED]> wrote: >Duncan Booth wrote: > >> Franz Steinhaeusler <[EMAIL PROTECTED]> wrote: >> >>> Hello, I'm only curious. >>> >>> Why is Python and most extension (also wxPython) not built using an >>> open source compiler like gcc or g++ on Windows? >>> >>> I'm always wondering, why Microsoft is still supported >>> in that way, using VC++ 7.1, if I'm not wrong. >>> >>> Ok, maybe the compiled assembler code could be better, but >>> this cannot be the reason, or? >>> >>> It would be wonderful (from the principle) if this could be possible. >>> From the standpoint of open source. >>> >>> What are your opinions? >> >> Practicality beats purity. >> >> To maximise the interoperability of Python with other software on the >> platform it makes sense to use the best supported compiler environment for >> the platform. @Duncan: Yes, you are not wrong! :) But this is not really open source in my opinion. Ok there is the VC++ toolkit for download. I'm just curious, if there ever had compiled on windows using that toolkit or even with gcc, and with gcc, whether there are problems or/and differences in speed and run time behaviour. > >Still, if one considers the many threads of people trying to get it to work >with the "free" version + other people that had to invest in VS mostly for >that (I did) / it might eventually be fair to reconsider. > >+ a dll is a dll > >hg @hg: that would be cool. -- http://mail.python.org/mailman/listinfo/python-list
Re: Taint (like in Perl) as a Python module: taint.py
"Gabriel Genellina" <[EMAIL PROTECTED]> writes: > I'm not convinced at all of the usefulness of tainting. > How do you "untaint" a string? By checking some conditions? In perl? I don't think you can untaint a string, but you can make a new untainted string by extracting a regexp match from the tainted string's contents. > Let's say, you validate and untaint a string, regarding it's future > usage on a command line, so you assume it's safe to use on os.system > calls - but perhaps it still contains a sql injection trap (and being > untainted you use it anyway!). Well, ok, you didn't check it carefully enough, but at least you made an attempt. Taint checking is a useful feature in perl. > Tainting may be useful for a short lived string, one that is used on > the *same* process as it was created. And in this case, unit testing > may be a good way to validate the string usage along the program. Unit testing is completely overrated for security testing. It checks the paths through the program that you've written tests for. Taint checking catches errors in paths that you never realized existed. > - for sql injection, use parametrized queries, don't build SQL > statements by hand. > - for html output, use any safe template engine, always quoting inputs. > - for os.system and similar, validate the command line and arguments > right before being executed. and so on. Right, but it's easy to make errors and overlook things, and taint checking catches a lot of such mistakes. -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling J from Python
On Feb 6, 3:04 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > On Feb 5, 8:48 am, "Gosi" <[EMAIL PROTECTED]> wrote: > > > It is quite easy to call J from Python > > >http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... > > There are a couple of issue that should be adressed. Am I going to > jail if I write a program and then redistribute all the files required > to run the program I write?? J is free for anyone to download and use. If someone is interested in putting you in jail it will not because you distribute J or redistribute the J utilities. > The second is how do I use the j stuff > without learning all that much about j. Just like Python then how much time you spend is uo to you. If you want to be good at it you may have to spend some time. You may also be just a casual user and dip into it now and again. There are lots of Demos, Labs and Help files besides all the utilities. You can freely use the utilities and examples to create your own application. You can write code in conventional style and not spend any time on the advanced functionality. > I am just intrested in > stealing graphics libraries and using what I have already written in > python.. There are a number of graphics examples, utilities and demos you can use in J and combine it with Python. The new grid classes in J are amazingly useful too. I am just starting to learn Python and I find it interesting to combine it with J. I know a few people who are doing so successfully. There are always some nicetise in any language that can be beneficial. Combining them enhances both. http://groups.google.com/group/j-programming http://jsoftware.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Count nb call of a function, without global var or decorator
"Méta-MCI" <[EMAIL PROTECTED]> wrote: > Example, with meta-data (attributs of function) : > > def ff(this): > try: > this.count=this.count+1 > except: > this.count=1 > a=1 > b=2 > c=a+b > > ff(ff) > fa=ff > ff(ff) > fa(fa) > print ff.count > > > > How to improve that? If I've managed to guess what you are asking, you want to use a class: >>> class Ff: def __init__(self): self.count = 0 def __call__(self, notused): self.count += 1 a, b = 1, 2 c = a+b return c >>> ff = Ff() >>> fa = Ff() >>> ff(ff) 3 >>> ff.count 1 >>> fa.count 0 -- http://mail.python.org/mailman/listinfo/python-list
Re: problems loading modules
Thanks guys! -- http://mail.python.org/mailman/listinfo/python-list
Re: Python compiled on Windows
Franz Steinhaeusler <[EMAIL PROTECTED]> wrote: > @Duncan: Yes, you are not wrong! :) > But this is not really open source in my opinion. > Ok there is the VC++ toolkit for download. Which I agree totally is a real pain finding the right versions to download. > > I'm just curious, if there ever had compiled on windows using > that toolkit or even with gcc, and with gcc, whether there are > problems or/and differences in speed and run time behaviour. > Yes, people have compiled Python with gcc on windows. I believe it is slightly slower than the standard release, but I would guess that may depend on the exact versions of gcc/msc you choose to compare, and the exact compiler options you choose (or I may even be imagining it entirely). As I understand it, you can use Mingw to compile extension modules which are compatible with the standard release of Python, and of course there is always cygwin. But I still don't understand what difference it makes to anyone between: an application (could be open or closed source) running on an open source language (Python) compiled with a closed source compiler on a closed source OS. versus an application (could be open or closed source) running on an open source language (Python) compiled with an open source compiler on a closed source OS. at the end of the day you still have a mix of open and closed source components. If it makes you feel better to be using an open source compiler that's fine, but it doesn't really do anything for me. -- http://mail.python.org/mailman/listinfo/python-list
Re: HTMLParser's start_tag method never called ?
On 29 jan, 16:45, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> ychaouche wrote:
> > Hi, python experts.
>
> >
> > [EMAIL PROTECTED]:~/TEST$ python nettoyageHTML.py
> > [EMAIL PROTECTED]:~/TEST$
> >
>
> > This is the nettoyageHTML.py python script
>
> >
> > fromHTMLParserimportHTMLParser
>
> > class ParseurHTML(HTMLParser):
> > def __init__(self):
> >HTMLParser.__init__(self)
>
> > def start_body(self,attrs):
> > print "this is my body"
>
> > p = ParseurHTML()
> > p.feed(open("/home/chaouche/TEST/AJAX/testXMLRPC.html","r").read())
> >
>
> > this is the testXMLRPC.html html file :
>
> >
> >
> > > src="ClientXMLRPC.js">
> >
>
> >
>
> > if (typeof netscape != 'undefined' && typeof netscape.security !=
> > 'undefined') {
>
> > netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserRea
> > d');
> > }
>
> > var chiffre = 0;
> > handler = function (self){
> > if (self.xmlhttp.readyState == 4) {
> > reponse = self.xmlhttp.responseText;
> > //dump(reponse); permet d'acceder au dom si ce qu'on a recu est une
> > forme de xml.
> > document.getElementById("txt").innerHTML=reponse;
> > }
> > }
>
> > function recupDonnees(){
> > chiffre+=1;
> > client = new ClientXMLRPC();
> > client.setUrl("http://10.75.49.100:8081/bonjour/sayHi?
> > chiffre="+chiffre);
> > client.executer();
> > client.handlerEvenement = handler;
> > }
> > recupDonnees();
>
> >
> >
> >
>
> > NON
> >
> >
>
> > The script should output "this is my body", but nothing is printed.
> > Anyone ?
>
> You need a p.close() after the feed I guess.
>
> Diez
I tried p.close() and nothing happens.
Y.Chaouche
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python compiled on Windows
On 6 Feb 2007 08:35:08 GMT, Duncan Booth <[EMAIL PROTECTED]> wrote: >Franz Steinhaeusler <[EMAIL PROTECTED]> wrote: > >> @Duncan: Yes, you are not wrong! :) >> But this is not really open source in my opinion. >> Ok there is the VC++ toolkit for download. > >Which I agree totally is a real pain finding the right versions to >download. > >> >> I'm just curious, if there ever had compiled on windows using >> that toolkit or even with gcc, and with gcc, whether there are >> problems or/and differences in speed and run time behaviour. >> > >Yes, people have compiled Python with gcc on windows. I believe it is >slightly slower than the standard release, but I would guess that may >depend on the exact versions of gcc/msc you choose to compare, and the >exact compiler options you choose (or I may even be imagining it >entirely). I cannot imagine, that there is a decisive difference, especially as in gcc, you have also a couple of options. > >As I understand it, you can use Mingw to compile extension modules which >are compatible with the standard release of Python, and of course there >is always cygwin. > >But I still don't understand what difference it makes to anyone between: > >an application (could be open or closed source) running on an open >source language (Python) compiled with a closed source compiler on a >closed source OS. > >versus > >an application (could be open or closed source) running on an open >source language (Python) compiled with an open source compiler on a >closed source OS. For me it's more a issue of "principle". :) Ok, the OS is as it is, but the "layer" is more open. If there would be no toolkit, you have to buy (and many have bought Visual Studio) for open source projects, and that is the point, where I cannot make friend with me. > >at the end of the day you still have a mix of open and closed source >components. If it makes you feel better to be using an open source >compiler that's fine, but it doesn't really do anything for me. Ok, I let your opinion, it is also fine with me! :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Finding cpu time spent on my program
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote: > On Feb 5, 2:37 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> > wrote: > > I am trying to measure the time the processor spends on some > > operation, and I want this measure to not depend on the current load > > of the machine. > > One of the best ways to time small snippets of code is python's timeit > module. See the docs at > http://docs.python.org/lib/module-timeit.html Timeit is very cool, but it doesn't measure CPU time, it measure real time, eg on a linux box $ python -m timeit 'for i in xrange(10): pass' 100 loops, best of 3: 11.4 msec per loop Now run 10 copies of the same program at once $ for i in `seq 10` ; do python -m timeit 'for i in xrange(10): pass' & done 10 loops, best of 3: 24.4 msec per loop 10 loops, best of 3: 83.2 msec per loop 10 loops, best of 3: 83.4 msec per loop 10 loops, best of 3: 81.4 msec per loop 10 loops, best of 3: 83 msec per loop 10 loops, best of 3: 60.7 msec per loop 10 loops, best of 3: 47 msec per loop 10 loops, best of 3: 48.6 msec per loop 10 loops, best of 3: 42.3 msec per loop 10 loops, best of 3: 38.7 msec per loop > > Is there a way to measure the number of cpu cycles spent on my program > > alone irrespective of the current load etc of the machine. The most accurate way of measuring CPU usage under linux is getrusage, eg >>> import resource >>> def cpu_time(): ... return resource.getrusage(resource.RUSAGE_SELF)[0] ... Now try this out >>> def f(): ... for i in xrange(10): ... pass ... >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.008001 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.012001 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.012 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.012001 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.016001 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.012001 >>> start = cpu_time(); f(); dt = cpu_time() - start; print dt 0.008001 You'll see the result is quantised to 4 ms (not sure what the .01 bits are about!) 4ms is the clock rate of this machine, ie 250 Hz. This is a compile time option for the linux kernel and is usually set in the range 100 Hz to 1000 Hz. The kernel doesn't measure CPU usage more accurately than this. -- Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Taint (like in Perl) as a Python module: taint.py
On Feb 6, 3:01 am, Ben Finney <[EMAIL PROTECTED]>
wrote:
> "Gabriel Genellina" <[EMAIL PROTECTED]> writes:
> > And tainted() returns False by default?
> > Sorry but in general, this won't work :(
>
> I'm inclined to agree that the default should be to flag an object as
> tainted unless known otherwise.
That's true. For example, my first attempt didn't prevent this:
os.open(buffer('/etc/passwd'), os.O_RDONLY)
Here's a stricter version:
def tainted(param):
"""
Check if a parameter is tainted. If it's a sequence or dict, all
values will be checked (but not the keys).
"""
if isinstance(param, unicode):
return not isinstance(param, SafeString)
elif isinstance(param, (bool, int, long, float, complex, file)):
return False
elif isinstance(param, (tuple, list)):
for element in param:
if tainted(element):
return True
elif isinstance(param, dict):
return tainted(param.values())
else:
return True
--
http://mail.python.org/mailman/listinfo/python-list
How to prevent from race conditions to share data between many process and thread in python
I use TurboGears to do some web service. TurboGears use cherrypy. When web browser access this site, the cherrypy will call my python program. So my program looks like a lib. When web browser access the site, the http server will fock a process or gerenate a thread. I need share some data or operate some files. How can I prevent from race conditions. Is there any way can I lock this. Thank you in advance! -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling J from Python
On Feb 5, 3:48 pm, "Gosi" <[EMAIL PROTECTED]> wrote: > It is quite easy to call J from Python > > http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... As I understand it, the k language, which is similar to J, is used to interact with streamed realtime financial data, where I imagine the terseness of the language may make sense. I messed about with J for a day or two, and found it interesting and in a way natural (given some Higher Math background once upon a time). Here's a link to a company who it looks like could value some knowledge of J/K/APL type languages: http://www.kx.com/news/in-the- news.php All the best Gerard -- http://mail.python.org/mailman/listinfo/python-list
Re: How to suppress "DeprecationWarning: Old style callback, use cb_func(ok, store) instead"
"Gabriel Genellina" <[EMAIL PROTECTED]> wrote: > En Sat, 03 Feb 2007 07:35:22 -0300, Peter Otten <[EMAIL PROTECTED]> > escribió: >> #!/usr/bin/env python2.5 >> >> python2.5 will be that single argument and no options are possible at >> all. >> What might be the reasons for such a seemingly arbitrary limitation? > The shell parses that line, not Python, so you should look into its > documentation. Bzzt! In any modestly recent Unix version (meaning fifteen years old or younger), it has been the kernel that parsed the #! line, not the shell. As for *how* the kernel parses that line, it varies between Unix versions. Linux, at least versions 2.4 and 2.6, takes everything after the interpreter and passes it as a single argument to the interpreter, with leading and trailing whitespace stripped. Thus #! /usr/bin/interpreter foo bar gazonk del will give the parameter "foo bar gazonk del" to the interpreter. SunOS 5.10 (aka Solaris 10) on the other hand, splits the line on whitespace and passes only the first word as parameter, and would thus give only "foo" to the interpreter for the same #! line. I seem to remember having used some Unix flavor that allowed multiple words as arguments, and thus passed the four words "foo", "bar", "gazonk" and "del" as arguments for the above #! line, but I don't remember what Unix that was. -- Thomas Bellman, Lysator Computer Club, Linköping University, Sweden "Adde parvum parvo magnus acervus erit" ! bellman @ lysator.liu.se (From The Mythical Man-Month) ! Make Love -- Nicht Wahr! -- http://mail.python.org/mailman/listinfo/python-list
Re: How to prevent from race conditions to share data between many process and thread in python
mars wrote: > I use TurboGears to do some web service. TurboGears use cherrypy. When > web browser access this site, the cherrypy will call my python > program. So my program looks like a lib. When web browser access the > site, the http server will fock a process or gerenate a thread. I need > share some data or operate some files. How can I prevent from race > conditions. Is there any way can I lock this. > Thank you in advance! There are the Lock and RLock objects available in the module threading. Diez -- http://mail.python.org/mailman/listinfo/python-list
XMLRPC Server
Hi, I'm trying to create an XMLRPC server using apache + python (cgi). It's not too difficult to configure everything, but I would like to tune it in order to receive up to 2000 calls per minute without any problems. Do Pthon CGIs use threading? I need to make it very efficient, but I haven't found much information about Python CGI optimization. The called function will update a table in a mysql db. I will use triggers to export data from the table updated by the xmlrpc server to other tables used by the backend application. any hint? lv -- http://mail.python.org/mailman/listinfo/python-list
Re: HTMLParser's start_tag method never called ?
ychaouche wrote: > class ParseurHTML(HTMLParser): > def __init__(self): > HTMLParser.__init__(self) > > def start_body(self,attrs): > print "this is my body" def start_tag(self, name, attrs): if name == 'body': print "this is my body" -- http://mail.python.org/mailman/listinfo/python-list
Two mappings inverse to each other: f, g = biject()
Hello As part of the MathTran project I found myself wanting to maintain a bijection between long names and short names. http://www.open.ac.uk/mathtran In other words, I wanted to have two dictionaries f and g such that f[a] == b g[b] == a are equivalent statements. A google search for biject.py and bijection.py produced no hits, so I suspect that this may not have been done before. I've written a partial implementation of this, and would appreciate comments. http://texd.cvs.sourceforge.net/texd/tex/util.py?revision=1.1&view=markup http://texd.cvs.sourceforge.net/texd/test_tex/test_util.py?revision=1.1&view=markup Here's the code from test_util.py, that shows how it works. The weakref stuff is so that there isn't a circular reference f to g to f. === from tex.util import biject f, g = biject() assert f.inverse is g assert g.inverse is f f[1] = 2 assert f[1] == 2 assert g[2] == 1 assert f.has_value(2) import weakref wr_g = weakref.ref(g) del g assert wr_g() == None assert f.inverse == None === best regards Jonathan -- http://mail.python.org/mailman/listinfo/python-list
Re: XMLRPC Server
[EMAIL PROTECTED] wrote: > Hi, I'm trying to create an XMLRPC server using apache + python (cgi). > It's not too difficult to configure everything, but I would like to > tune it in order to receive up to 2000 calls per minute without any > problems. Do Pthon CGIs use threading? > I need to make it very efficient, but I haven't found much information > about Python CGI optimization. > The called function will update a table in a mysql db. I will use > triggers to export data from the table updated by the xmlrpc server to > other tables used by the backend application. You might consider using the twisted application server framework instead, and totally ditch the CGI, and even the apache. http://twistedmatrix.com/ http://twistedmatrix.com/projects/web/documentation/examples/xmlrpc.py Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Python cheatsheets
robert wrote: > gonzlobo wrote: >> Curious if anyone has a python cheatsheet* published? I'm looking for >> something that summarizes all commands/functions/attributes. Having >> these printed on a 8" x 11" double-sided laminated paper is pretty >> cool. >> >> * cheatsheet probably isn't the right word, but you get the idea. :) > > search: python quick reference > > e.g.: http://www.benyoonline.com/pqr/pqr24/PQR2.4.html ... and be aware that the "quick" reference currently runs to seventeen or eighteen sides ... it should really be renamed "comprehensive reference", though it does currently omit the kitchenSink module :) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 -- http://mail.python.org/mailman/listinfo/python-list
Repr or Str ?
Where and when is good/nescessary to use `repr` instead of `str` ? Can you please explain the differences Thanks LL -- http://mail.python.org/mailman/listinfo/python-list
Re: Repr or Str ?
On Feb 6, 11:47 am, "Johny" <[EMAIL PROTECTED]> wrote: > Where and when is good/nescessary to use `repr` instead of `str` ? > Can you please explain the differences > Thanks RTFM. http://docs.python.org/ref/customization.html __repr__( self) Called by the repr() built-in function and by string conversions (reverse quotes) to compute the ``official'' string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form "<...some useful description...>" should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an ``informal'' string representation of instances of that class is required. This is typically used for debugging, so it is important that the representation is information-rich and unambiguous. __str__( self) Called by the str() built-in function and by the print statement to compute the ``informal'' string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object. -- http://mail.python.org/mailman/listinfo/python-list
Re: Repr or Str ?
str is a text representation of the object, you can see it as a nice print repr is the text representation of the object that you can evaluate to get the same object Johny wrote: > Where and when is good/nescessary to use `repr` instead of `str` ? > Can you please explain the differences > Thanks > LL > > -- http://mail.python.org/mailman/listinfo/python-list
Re: Repr or Str ?
"Johny" <[EMAIL PROTECTED]> wrote: > Where and when is good/nescessary to use `repr` instead of `str` ? > Can you please explain the differences roughly, repr() is for programmers, str() is for end-users. -- http://mail.python.org/mailman/listinfo/python-list
Re: lambda functions ?
> This means that "f" is not a pointer to make_incrementor but rather to > the internal (copied?) function. "returned" function isthe right here. As any returned object from a function. > > > This style is very common in Scheme programming so you might read a > > Scheme book if you want to understand it. The classic: > > > > http://mitpress.mit.edu/sicp/ > > > > I might just well do that. A nice read indeed, but understand this concept first: http://en.wikipedia.org/wiki/First-class_function -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt Blog: http://edcrypt.blogspot.com Jabber: edcrypt at jabber dot org ICQ: 161480283 GTalk: eduardo dot padoan at gmail dot com MSN: eopadoan at altavix dot com -- http://mail.python.org/mailman/listinfo/python-list
Re: Python cheatsheets
On Jan 7, 10:11 pm, Jussi Salmela <[EMAIL PROTECTED]> wrote: > gonzlobo kirjoitti: > > > Curious if anyone has a python cheatsheet* published? I'm looking for > > something that summarizes all commands/functions/attributes. Having > > these printed on a 8" x 11" double-sided laminated paper is pretty > > cool. > > > * cheatsheet probably isn't the right word, but you get the idea. :) > > http://rgruet.free.fr/ "cheatsheet"? That´s twice O´Reilly's "Python: Pocket Reference". ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Inheriting str object
On 5 feb, 11:48, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> I want to have a str with custom methods, but I have this problem:
>
> class myStr(str):
> def hello(self):
> return 'hello '+self
>
> s=myStr('world')
> print s.hello() # prints 'hello world'
> s=s.upper()
> print s.hello() # expected to print 'hello WORLD', but s is no longer
> myStr, it's a regular str!
>
> What can I do?
I'm new to this list(this is my first message) and to Python also (I'm
learning these days), so i'm afraid that this is not what you are
asking for but anyway
you can create an myStr object on the fly, something like:
s=myStr(s.upper())
Alex
--
http://mail.python.org/mailman/listinfo/python-list
Re: XMLRPC Server
Unfortunately I have to use Apache. The server implementation will we very easy, so I'm also considering more efficient solutions than python lv On Feb 6, 11:36 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Hi, I'm trying to create an XMLRPC server using apache + python (cgi). > > It's not too difficult to configure everything, but I would like to > > tune it in order to receive up to 2000 calls per minute without any > > problems. Do Pthon CGIs use threading? > > I need to make it very efficient, but I haven't found much information > > about Python CGI optimization. > > The called function will update a table in a mysql db. I will use > > triggers to export data from the table updated by the xmlrpc server to > > other tables used by the backend application. > > You might consider using the twisted application server framework instead, > and totally ditch the CGI, and even the apache. > > http://twistedmatrix.com/ > > http://twistedmatrix.com/projects/web/documentation/examples/xmlrpc.py > > Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: XMLRPC Server
Unfortunately I have to use Apache. The server implementation will be very easy, so I'm also considering more efficient solutions than python lv On Feb 6, 11:36 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Hi, I'm trying to create an XMLRPC server using apache + python (cgi). > > It's not too difficult to configure everything, but I would like to > > tune it in order to receive up to 2000 calls per minute without any > > problems. Do Pthon CGIs use threading? > > I need to make it very efficient, but I haven't found much information > > about Python CGI optimization. > > The called function will update a table in a mysql db. I will use > > triggers to export data from the table updated by the xmlrpc server to > > other tables used by the backend application. > > You might consider using the twisted application server framework instead, > and totally ditch the CGI, and even the apache. > > http://twistedmatrix.com/ > > http://twistedmatrix.com/projects/web/documentation/examples/xmlrpc.py > > Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: XMLRPC Server
[EMAIL PROTECTED] wrote: > Hi, I'm trying to create an XMLRPC server using apache + python (cgi). > It's not too difficult to configure everything, but I would like to > tune it in order to receive up to 2000 calls per minute without any > problems. That doesn't seem like excessive volume. Why not just try it? You could replace your database logic with time.sleep(1) for now. > Do Pthon CGIs use threading? To do what? CGI requires that a new interpreter instance be launched to handle every request. The requests will be handled in parallel with the number of requests handled simultaneously depending on your apache configuration. > I need to make it very efficient, Actually, you might not have to. 2000 calls/minute isn't that big, assuming you have a decent server. Cheers, Brian -- http://mail.python.org/mailman/listinfo/python-list
Re: XMLRPC Server
On 6 Feb, 12:30, "Lorenzo" <[EMAIL PROTECTED]> wrote: > Unfortunately I have to use Apache. The server implementation will we > very easy, so I'm also considering more efficient solutions than > python You could try mod_python if there isn't an absolute requirement for CGI: http://www.modpython.org/ Some people might recommend other frameworks which operate in separate long-running processes, but if you don't have the freedom to have such processes, you might wish to consider focusing on the start-up costs of your CGI programs. Once upon a time, CGI was deemed very expensive because process creation was itself expensive, and many database- related CGI programs had to open connections to database systems whose connection costs were very expensive (eg. Oracle). While not spawning new processes and not opening and closing database connections avoids such costs, it is worth reviewing just how expensive such things are on modern operating systems (on modern hardware) and with other database systems (such as MySQL, which you said you were using). Ultimately, some benchmarking/profiling will indicate whether your performance expectations are realistic. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: How to prevent from race conditions to share data between many process and thread in python
On 2月6日, 下午6时14分, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > mars wrote: > > I use TurboGears to do some web service. TurboGears use cherrypy. When > > web browser access this site, the cherrypy will call my python > > program. So my program looks like a lib. When web browser access the > > site, the http server will fock a process or gerenate a thread. I need > > share some data or operate some files. How can I prevent from race > > conditions. Is there any way can I lock this. > > Thank you in advance! > > There are the Lock and RLock objects available in the module threading. > > Diez Can this also lock mutil-process? -- http://mail.python.org/mailman/listinfo/python-list
Re: Python cheatsheets
On Jan 7, 10:03 pm, gonzlobo <[EMAIL PROTECTED]> wrote: > Curious if anyone has a python cheatsheet* published? I'm looking for > something that summarizes all commands/functions/attributes. Having > these printed on a 8" x 11" double-sided laminated paper is pretty > cool. > > * cheatsheet probably isn't the right word, but you get the idea. :) http://www.onlamp.com/python/excerpt/PythonPocketRef/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to prevent from race conditions to share data between many process and thread in python
mars wrote: > On 2月6日, 下午6时14分, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: >> mars wrote: >> > I use TurboGears to do some web service. TurboGears use cherrypy. When >> > web browser access this site, the cherrypy will call my python >> > program. So my program looks like a lib. When web browser access the >> > site, the http server will fock a process or gerenate a thread. I need >> > share some data or operate some files. How can I prevent from race >> > conditions. Is there any way can I lock this. >> > Thank you in advance! >> >> There are the Lock and RLock objects available in the module threading. >> >> Diez > > Can this also lock mutil-process? No. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Two mappings inverse to each other: f, g = biject()
On Feb 6, 5:22 am, Jonathan Fine <[EMAIL PROTECTED]> wrote:
> Hello
>
> As part of the MathTran project I found myself
> wanting to maintain a bijection between long
> names and short names.
>http://www.open.ac.uk/mathtran
>
> In other words, I wanted to have two dictionaries
> f and g such that
>f[a] == b
>g[b] == a
> are equivalent statements.
>
> A google search for biject.py and bijection.py
> produced no hits, so I suspect that this may not
> have been done before.
>
> I've written a partial implementation of this,
> and would appreciate comments.
>
> http://texd.cvs.sourceforge.net/texd/tex/util.py?revision=1.1&view=ma...http://texd.cvs.sourceforge.net/texd/test_tex/test_util.py?revision=1...
>
> Here's the code from test_util.py, that shows how it
> works. The weakref stuff is so that there isn't a
> circular reference f to g to f.
> ===
> from tex.util import biject
>
> f, g = biject()
> assert f.inverse is g
> assert g.inverse is f
>
> f[1] = 2
> assert f[1] == 2
> assert g[2] == 1
> assert f.has_value(2)
>
> import weakref
>
> wr_g = weakref.ref(g)
> del g
> assert wr_g() == None
> assert f.inverse == None
> ===
>
> best regards
>
> Jonathan
Jonathan,
If you need to get a short name, given a long name or vice-verse _and_
the set of short names and long names is distinct (it would be
confusing if it wasn't!) then you can just have one dictionary, no
need to complicate things too much:
f[a]=b
f[b]=a
You won't know which is a short and which is a long based just on
this, so you need to keep track of it. But it will give you the
mapping.
Here is an example:
>>> S=('a','b','d')
>>> L=('alpha,'beta','delta')
>>> f={}
>>> for i in range(3):
: f[S[i]]=L[i]
: f[L[i]]=S[i]
>>> f
{'a': 'alpha',
'alpha': 'a',
'b': 'beta',
'beta': 'b',
'd': 'delta',
'delta': 'd'}
>>> f['b']
'beta'
>>> f['beta']
'b'
--
Hope this helps,
And remember : "Simple Is Better Than Complex" [http://www.python.org/
doc/Humor.html#zen]
Nick Vatamaniuc
--
http://mail.python.org/mailman/listinfo/python-list
Re: Repr or Str ?
On Feb 6, 5:47 am, "Johny" <[EMAIL PROTECTED]> wrote: > Where and when is good/nescessary to use `repr` instead of `str` ? > Can you please explain the differences > Thanks > LL When you want to provide a representation of an object from which you can create another object if you had to. Use 'str' if you just want to print it nicely. -- http://mail.python.org/mailman/listinfo/python-list
Re: C parsing fun
Helo again! When I came up with this idea on how to parse C files with ease, I was at home and I only have access to the sources in subject in the office. So I've tried the previously posted algorithm on the actual source today and I realized my originally example data I've ran the test with was so simple, that with some header files the algorithm still failed. I had to make some further changes and by now I was able to parse 1135 header files in 5 seconds with no errors. This may be considered as spamming, but this package is so small I don't wan't to create a page for it on SF or Google Code. Furthermore I want to provide people who find this topic a working solution, so here's the latest not-so-elegant-brute-force-but-fast parser: http://kiri.csing.hu/stack/python/bloppy-0.3.zip On Feb 5, 1:43 pm, "karoly.kiripolszky" <[EMAIL PROTECTED]> wrote: > Helo ppl! > > At the job I was given the task to make a script to analyze C++ code > based on concepts my boss had. To do this I needed to represent C++ > code structure in Python somehow. I read the docs for Yapps, pyparsing > and other stuff like those, then I came up with a very simple idea. I > realized that bracketed code is almost like a Python list, except I > have to replace curly brackets with squared ones and surround the > remaining stuff with quotes. This process invokes no recursion or node > objects, only pure string manipulations so I believe it's really fast. > Finally I can get the resulting list by calling eval() with the > string. > > For example when I need to parse a class definition, I only need to > look for a list item containing the pattern "*class*", and the next > item will be the contents of the class as another list. > > You can grab the code at: > > http://kiri.csing.hu/stack/python/bloppy-0.1.zip > > (test script [test.py] included) -- http://mail.python.org/mailman/listinfo/python-list
Re: when will python 2.5 take in mainstream?
On Feb 5, 4:15 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: > It's very easy to maintain compatibility in the C API. I'm much more > interested in compatibility at the Python layer, which is changed > incompatibly much, much more frequently than is the C layer. Really? In all cases I've found, pure-Python extensions written for 2.4 work with 2.5. The same was true for 2.3 to 2.4 as well. And even if I found one that didn't, it's highly likely I could fix it myself. The same doesn't apply to any C compiled extensions. Updating Python breaks these, every time, and users typically have to wait months for the library developer to compile a new version, every time. Or maybe they can wade through the morass of "how do I compile this library on Windows" threads here. Perhaps the C API remains the same but the real issue is the binary API between extensions and Python changes every couple of years or so. That's why I run 2.4 anywhere that needs extensions. It would be great if someone could invest some time in trying to fix this problem. I don't think I know of any other languages that require recompilation of libraries for every minor version increase. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Format a float and put in a list
Hello, I have a float that I am trying to format to 2 decimal places, put the formatted float in a list and then output this to a file. My problem is, once I format my float, my float has quotations around the float due to my formatting. I am doing the following: ( "%.2f" % float( list[x] ) ) Is there a way I can format the float so when I see it in the file it looks like [19.45, 20.52, 16.56] instead of ['19.45', '20.52', '16.56']? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
Graphs, bar charts, etc
Hello all, I have some data in a postgresql table which I view through a web interface (the web interface is written in python -- using mod_python under apache 2.2). Now I would like to represent this data as graphs, bar charts, etc. I know about matplotlib, and it seemed like exactly what I was looking for. I tried importing it in my script, but it gave me some error about a home directory not being writable. I'm not sure I like the idea of it require to be able to write somewhere. Am I using it wrong? Is there something else I can use which can produce graphs easily? -- Kind regards, Jan Danielsson -- http://mail.python.org/mailman/listinfo/python-list
Re: List Behavior when inserting new items
[EMAIL PROTECTED] wrote: > On Jan 29, 7:57 pm, "Drew" <[EMAIL PROTECTED]> wrote: >> I'm looking to add an element to list of items, however I'd like to >> add it at a specific index greater than the current size: >> >> list = [1,2,3] >> list.insert(10,4) >> >> What I'd like to see is something like: >> >> [1,2,3,,4] >> >> However I see: >> >> [1,2,3,4] >> >> Is there any way to produce this kind of behavior easily? >> >> Thanks, >> Drew > > You could write your own class mimicing a list with your desired > behaviour, something like: > > py>class llist(object): > py>def __init__(self, arg = []): > py>self.__list = arg > py>def __setitem__(self, key, value): > py>length = len(self.__list) > py>if length < key: > py>for i in range(length, key +1): > py>self.__list.append(None) > py>self.__list[key] = value > py>def __str__(self): > py>return str(self.__list) > py> > py>x = llist() > py>x[10] = 1 > py>print x > [None, None, None, None, None, None, None, None, None, None, 1] > > for other methods to add to the llist class see http://docs.python.org/ > ref/sequence-types.html > or like this >>> class Llist(list): def __init__(self): list.__init__(self) def insertatindex(self, index, value): lenght = len(self) if lenght < index: for i in range(lenght, index): self.append(None) self.insert(index, value) -- http://mail.python.org/mailman/listinfo/python-list
Running long script in the background
Hello, I am trying to write a python cgi that calls a script over ssh, the problem is the script takes a very long time to execute so Apache makes the CGI time out and I never see any output. The script is set to print a progress report to stdout every 3 seconds but I never see any output until the child process is killed. Here's what I have in my python script: command = "ssh -l root %s /scripts/xen/xen-create-win-vps1.sh %s" % (host, domuname) output = os.popen(command) for line in output: print line.strip() Here's a copy of the bash script. http://watters.ws/script.txt I also tried using os.spawnv to run ssh in the background and nothing happens. Does anybody know a way to make output show in real time? -- http://mail.python.org/mailman/listinfo/python-list
Re: Two mappings inverse to each other: f, g = biject()
Nick Vatamaniuc wrote: > If you need to get a short name, given a long name or vice-verse _and_ > the set of short names and long names is distinct (it would be > confusing if it wasn't!) then you can just have one dictionary, no > need to complicate things too much: > f[a]=b > f[b]=a > You won't know which is a short and which is a long based just on > this, so you need to keep track of it. But it will give you the > mapping. Thank you for this suggestion, Nick. It's not something I thought of. And I'm sure that in some cases it might be just the right thing. It would hold something like 'other-name' values. (Every cat should have at least two names ...) But for my application, I think it complicates the code that uses the bijection. For example, I want to say: # Write the font dictionary to a file for key in font_dict: # write the font # Does value already exist in the font dictionary? # If not, add it to the font dictionary. key = font_dict.inverse.get(value) if key is None: key = len(font_dict) font_dict[key] = value Following your suggestion, ingenious though it is, would make the above code much more complicated and error prone. Perhaps it helps to think of f, g = biject() as establishing a database, that has a consistency condition, and which has two views. There we are: biject() gives two views on a mapping (of a particular type). Thank you for you suggestion - it has clarified my thinking. -- Jonathan -- http://mail.python.org/mailman/listinfo/python-list
Re: Running long script in the background
> Does anybody know a way to make output show in real time? You can put: #!/usr/bin/python -u at the top of the script to have unbuffered binary stdout and stderr. -- http://mail.python.org/mailman/listinfo/python-list
Re: when will python 2.5 take in mainstream?
On 6 Feb, 13:45, "Ben Sizer" <[EMAIL PROTECTED]> wrote: > > Perhaps the C API remains the same but the real > issue is the binary API between extensions and Python changes every > couple of years or so. That's why I run 2.4 anywhere that needs > extensions. > > It would be great if someone could invest some time in trying to fix > this problem. I don't think I know of any other languages that require > recompilation of libraries for every minor version increase. On the python-dev mailing list there was discussion of some of these issues in the context of the Linux Standard Base specifications: http://mail.python.org/pipermail/python-dev/2006-November/070027.html Despite the specificity implied by the LSB name, I think such work would produce benefits for all Python developers with similar concerns, regardless of their chosen platforms. Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: when will python 2.5 take in mainstream?
On 6 Feb 2007 04:45:35 -0800, Ben Sizer <[EMAIL PROTECTED]> wrote: >On Feb 5, 4:15 pm, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: >> It's very easy to maintain compatibility in the C API. I'm much more >> interested in compatibility at the Python layer, which is changed >> incompatibly much, much more frequently than is the C layer. > >Really? In all cases I've found, pure-Python extensions written for >2.4 work with 2.5. The same was true for 2.3 to 2.4 as well. And even >if I found one that didn't, it's highly likely I could fix it myself. If you have to fix it yourself, then it's broken, wouldn't you say? Huge amounts of my pure Python code was broken by Python 2.5. So yes, it happens. The same _wasn't_ true for 2.3 to 2.4 though. Python 2.5 was pretty unusual in this regard. > >The same doesn't apply to any C compiled extensions. Updating Python >breaks these, every time, and users typically have to wait months for >the library developer to compile a new version, every time. Or maybe >they can wade through the morass of "how do I compile this library on >Windows" threads here. Perhaps the C API remains the same but the real >issue is the binary API between extensions and Python changes every >couple of years or so. That's why I run 2.4 anywhere that needs >extensions. Sure, this happens too. I didn't suggest it doesn't, I just pointed out that I was less interested in it. :) Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: Decimating Excel files
On Feb 5, 11:42 pm, "John Machin" <[EMAIL PROTECTED]> wrote: > On Feb 6, 1:19 pm, gonzlobo <[EMAIL PROTECTED]> wrote: > > > I tried to open the file with Kate, trust me, it's an Excel file. > > Who or what is Kate? In what sense is trying to open it any evidence > that it's an Excel file? Did you *succeed* in opening the file "with > Kate"? In the sense that Kate is not a girl, but a text editor. I assume he opened the file and got only "gibberish", instead of text, CSV, or whatever. Stephen -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphs, bar charts, etc
Jan Danielsson kirjoitti: > Hello all, > >I have some data in a postgresql table which I view through a web > interface (the web interface is written in python -- using mod_python > under apache 2.2). Now I would like to represent this data as graphs, > bar charts, etc. > >I know about matplotlib, and it seemed like exactly what I was > looking for. I tried importing it in my script, but it gave me some > error about a home directory not being writable. I'm not sure I like the > idea of it require to be able to write somewhere. Am I using it wrong? > >Is there something else I can use which can produce graphs easily? > I've used PyChart: http://home.gna.org/pychart/ in my Blood Pressure Monitor application: http://personal.inet.fi/cool/operator/BPMDownload.html I found PyChart to be very easy to use and to function as advertised. HTH, Jussi -- http://mail.python.org/mailman/listinfo/python-list
Re: "flushing"/demanding generator contents - implications for injection of control
On Feb 5, 3:08 pm, Jussi Salmela <[EMAIL PROTECTED]> wrote:
> metaperl kirjoitti:
>
> > For this program:
>
> > def reverse(data):
> > for index in range(len(data)-1, -1, -1):
> > yield data[index]
>
> > r = reverse("golf")
>
> > for char in r:
> > print char
>
> > I'm wondering if the line:
>
> > r = reverse("golf")
>
> > "demands" the contents of the function reverse() all at once and if I
> > must write
>
> > for char in reverse("golf"):
> > print char
>
> > if I want the results streamed instead of generated complely.
>
> > ** CONTEXT **
>
> > The simple example above is not what I am really doing. My real
> > program parses very large
> > data files using pyparsing. Pyparsing can generate incremental/yielded
> > results with no problem:
>
> >http://pyparsing.wikispaces.com/message/view/home/248539#248852
>
> > but because I believe in injection of control (pushing data around as
> > opposed to having
> > the target pull it), I get the parse and then inject it into the
> > generator:
>
> > parse = parsing.parse(fp.read())
> > txt = textgen.generate(self.storage.output, patent_key,
> > parse, f.basename(), debug=False)
>
> I don't know, I'm guessing:
>
> ... r = reverse("golf")
> ... type(r)
>
very slick! thanks!
> ... print r.next()
> f
>
> So r is not the string 'flog', it is the generator producing it
>
> HTH,
It does!
> Jussi
--
http://mail.python.org/mailman/listinfo/python-list
RE: Format a float and put in a list
Hello all, I found a workaround solution. I use the items in the list to be placed in a string, so I just formatted the entire string to remove any single quotes. Duh! Thanks From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of David Sulkin Sent: Tuesday, February 06, 2007 6:53 AM To: [email protected] Subject: Format a float and put in a list Hello, I have a float that I am trying to format to 2 decimal places, put the formatted float in a list and then output this to a file. My problem is, once I format my float, my float has quotations around the float due to my formatting. I am doing the following: ( "%.2f" % float( list[x] ) ) Is there a way I can format the float so when I see it in the file it looks like [19.45, 20.52, 16.56] instead of ['19.45', '20.52', '16.56']? Thanks in advance. -- http://mail.python.org/mailman/listinfo/python-list
How can I use __setitem__ method of dict object?
Please excuse me if this is obvious to others, but I can't figure it
out. I am subclassing dict, but want to prevent direct changing of
some key/value pairs. For this I thought I should override the
__setitem__ method as such:
class xs(dict):
"""
XS is a container object to hold information about cross sections.
"""
def __new__(cls, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
"""
"""
x = {}
x['xS'] = xS
x['xF'] = xF
x['nu'] = nu
x['xG'] = xG
x['xA'] = x['xG'] + x['xF']
x['xT'] = x['xA'] + x['xS']
return x
def __setitem__(self, key, value):
"""
I have overridden this method to prevent setting xT or xA
outside the
class.
"""
print "I am in __setitem__"
if key == 'xT':
raise AttributeError("""Can't change xT. Please change,
xF, xS, or xG""")
But I can't even get __setitem__ to run. Example:
Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import xs
>>> cs = xs.xs()
>>> cs
{'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': 3.0}
>>> cs['xT'] = 3.1415
>>> cs
{'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT':
3.14150002}
Is this what the __setitem__ method is for? If not, how can I do what
I want to do?
Thanks in advance,
Jeremy
--
http://mail.python.org/mailman/listinfo/python-list
Re: division by 7 efficiently ???
On Feb 1, 8:25 pm, "Krypto" <[EMAIL PROTECTED]> wrote: > The correct answer as told to me by a person is > (N>>3) + ((N-7*(N>>3))>>3) > The above term always gives division by 7 Does anybody else notice that this breaks the spirit of the problem (regardless of it's accuracy)? 'N-7' uses the subtraction operator, and is thus an invalid solution for the original question. Build a recursive function, which uses two arbitrary numbers, say 1 and 100. Check each, times 7, and make sure that your target number, N, is between them. Increase or decrease your arbitrary numbers as appropriate. Now pick a random number between those two numbers, and check it. Figure out which two the answer is between, and then check a random number in that subset. Continue this, and you will drill down to the correct answer, by using only *, +, >, and <. I'll bet money that since this was a programming interview, that it wasn't a check of your knowledge of obscure formulas, but rather a check of your lateral thinking and knowledge of programming. ~G -- http://mail.python.org/mailman/listinfo/python-list
Re: when will python 2.5 take in mainstream?
In article <[EMAIL PROTECTED]>, Ben Sizer <[EMAIL PROTECTED]> wrote: > >It would be great if someone could invest some time in trying to fix >this problem. I don't think I know of any other languages that require >recompilation of libraries for every minor version increase. How do you define "minor version increase"? If you look at the progression from 2.0 through 2.5, it's pretty clear that each version doesn't particularly fit "minor version increase" even though each one only increments by 0.1. -- Aahz ([EMAIL PROTECTED]) <*> http://www.pythoncraft.com/ "I disrespectfully agree." --SJM -- http://mail.python.org/mailman/listinfo/python-list
Re: Running long script in the background
[EMAIL PROTECTED] wrote: > Hello, > > I am trying to write a python cgi that calls a script over ssh, the > problem is the script takes a very long time to execute so Apache > makes the CGI time out and I never see any output. The script is set > to print a progress report to stdout every 3 seconds but I never see > any output until the child process is killed. > > Here's what I have in my python script: > > command = "ssh -l root %s /scripts/xen/xen-create-win-vps1.sh %s" % > (host, domuname) > output = os.popen(command) > for line in output: >print line.strip() try sys.stdout.flush() after every print. Or try something like this: import sys, time class FlushFile: def __init__(self, fd): self.fd = fd def flush(self): self.fd.flush() def write(self, str): self.fd.write(str) self.fd.flush() oldstdout = sys.stdout sys.stdout = FlushFile(sys.stdout) for i in range(5): print "Hello", time.sleep(0.5) print -- Thomas Güttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: Running long script in the background
On Feb 6, 8:36 am, "jasonmc" <[EMAIL PROTECTED]> wrote: > > Does anybody know a way to make output show in real time? > > You can put: #!/usr/bin/python -u > at the top of the script to have unbuffered binary stdout and stderr. Thanks. I tried that but it still times out waiting for output. Everything works fine until I call the popen function, then it freezes. What I want is to print the output in real time, just like it does when I run it from a shell. -- http://mail.python.org/mailman/listinfo/python-list
Re: glutInit and wxPython on Mac OSX
Artie wrote: > I seem to have uncovered a problem when using glutInit alongside > wxPython on Mac OSX. If glutInit is called prior to creating a > wx.App, many window and mouse events are either lost, not generated, > or misgenerated for the glcanvas. However, if glutInit is called > after the wx.App has been created then all is well. > > Has anyone ran across this issue before? If so, why does this order > matter or affect the wx Event system? > As to the whys and wherefores I cannot say, but there are many functions within the Wx package that require the application to be running before they can be called, so I presume glutInit makes use of some of those. Note that you can create a wx.App without creating windows visible on the screen. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden Blog of Note: http://holdenweb.blogspot.com See you at PyCon? http://us.pycon.org/TX2007 -- http://mail.python.org/mailman/listinfo/python-list
huge amounts of pure Python code broken by Python 2.5?
Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: > Huge amounts of my pure Python code was broken by Python 2.5. Interesting. Could you give a few illustrations of this? (I didn't run into the same problem at all, so I'm curious.) Steve -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I use __setitem__ method of dict object?
jeremito wrote:
> Please excuse me if this is obvious to others, but I can't figure it
> out. I am subclassing dict, but want to prevent direct changing of
> some key/value pairs. For this I thought I should override the
> __setitem__ method as such:
>
>
> class xs(dict):
> """
> XS is a container object to hold information about cross sections.
> """
>
> def __new__(cls, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
> """
> """
> x = {}
> x['xS'] = xS
> x['xF'] = xF
> x['nu'] = nu
> x['xG'] = xG
> x['xA'] = x['xG'] + x['xF']
> x['xT'] = x['xA'] + x['xS']
>
> return x
>
> def __setitem__(self, key, value):
> """
> I have overridden this method to prevent setting xT or xA
> outside the
> class.
> """
> print "I am in __setitem__"
> if key == 'xT':
> raise AttributeError("""Can't change xT. Please change,
> xF, xS, or xG""")
>
>
> But I can't even get __setitem__ to run. Example:
> Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
import xs
cs = xs.xs()
cs
> {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': 3.0}
cs['xT'] = 3.1415
cs
> {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT':
> 3.14150002}
>
>
> Is this what the __setitem__ method is for? If not, how can I do what
> I want to do?
>>> class d(dict):
... def __setitem__(self, k, v):
... print "Setting", k
... dict.__setitem__(self, k, v)
...
>>> dd = d()
>>> dd['steve'] = 'holden'
Setting steve
>>> dd['steve']
'holden'
>>>
I believe the problem is that your __new__ method does not return an
object of type xs but a dict, so it does not inherit the __getitem__
method from xs but instead from dict.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note: http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007
--
http://mail.python.org/mailman/listinfo/python-list
Re: Running long script in the background
On Feb 6, 10:37 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > On Feb 6, 8:36 am, "jasonmc" <[EMAIL PROTECTED]> wrote: > > > > Does anybody know a way to make output show in real time? > > > You can put: #!/usr/bin/python -u > > at the top of the script to have unbuffered binary stdout and stderr. > > Thanks. I tried that but it still times out waiting for output. > > Everything works fine until I call the popen function, then it > freezes. What I want is to print the output in real time, just like > it does when I run it from a shell. I tried flushing stdout and the same thing happens. As soon as the os.popen(command) line runs it stops there, the next print statement never even runs. I've also tried using os.spawnv to make the process run in the background but then the ssh command never runs. -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I use __setitem__ method of dict object?
On 6 fév, 16:23, "jeremito" <[EMAIL PROTECTED]> wrote:
> Please excuse me if this is obvious to others, but I can't figure it
> out. I am subclassing dict, but want to prevent direct changing of
> some key/value pairs. For this I thought I should override the
> __setitem__ method as such:
>
> class xs(dict):
> """
> XS is a container object to hold information about cross sections.
> """
>
> def __new__(cls, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
> """
> """
> x = {}
> x['xS'] = xS
> x['xF'] = xF
> x['nu'] = nu
> x['xG'] = xG
> x['xA'] = x['xG'] + x['xF']
> x['xT'] = x['xA'] + x['xS']
>
> return x
replace this with:
def __init__(self, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
dict.__init__(
self,
xS=xS,
xF=xF,
xG=xG,
nu=nu,
xA=xG + xF,
xT=xG + xF + xS
)
> def __setitem__(self, key, value):
> """
> I have overridden this method to prevent setting xT or xA
> outside the
> class.
> """
> print "I am in __setitem__"
> if key == 'xT':
> raise AttributeError(
"Can't change xT. Please change, xF, xS, or xG"
)
dict.__setitem__(self, key, value)
> But I can't even get __setitem__ to run.
of course, since your __new__ method returns a dict instance, not a xs
instance...
There are very few cases where you really need to override the __new__
method.
> Example:
> Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
> [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.>>>
> import xs
> >>> cs = xs.xs()
> >>> cs
>
> {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': 3.0}>>>
> cs['xT'] = 3.1415
> >>> cs
>
> {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT':
> 3.14150002}
>
> Is this what the __setitem__ method is for?
Yes. But note that you you need to manually call the superclass's
overriden method - unless you
really want to replace it with your own, which is obviously not the
case here...
Note that if someone manually changes the values of xG, xF, or xS, the
computed values of xA and/or xT
won't reflect this change. Is that what you want ?
Finally, and if I may ask, what is your use-case for subclassing
dict ? You don't need this to implement a dict-like object,
and it might be simpler in your case to write an ordinary class, then
add support for the required subset of the dict interface.
My 2 cents...
--
http://mail.python.org/mailman/listinfo/python-list
Re: huge amounts of pure Python code broken by Python 2.5?
Steven Bethard wrote: > Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: >> Huge amounts of my pure Python code was broken by Python 2.5. > > Interesting. Could you give a few illustrations of this? (I didn't run > into the same problem at all, so I'm curious.) > > Steve I can't think of any of my code that got broken and it fixed a broken SSL problem (on Windows) that I was fighting. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Why does list.__getitem__ return a list instance for subclasses of the list type?
>>> class ListyThing(list): pass ... >>> assert isinstance(ListyThing()[:], ListyThing) # I expect True! Traceback (most recent call last): File "", line 1, in AssertionError >>> type(ListyThing()[:]) # I expect ListyThing! I don't find this intuitive. Is this intentional? I believe this could be avoided if list.__getitem__ used "self.__class__()" to make a new instance, instead of "list()", but I don't know how that works under the hood in C. I believe this happens a lot of other cases too. Actually, I wrote up some test cases at http://brodierao.com/etc/listslice/ but I haven't taken a look at it in quite a while. I believe there's some other funky stuff going on there as well. Also, this happens with dict too: >>> class DictyThing(dict): pass ... >>> assert isinstance(DictyThing().copy(), DictyThing) # I expect True! Traceback (most recent call last): File "", line 1, in AssertionError >>> type(DictyThing().copy()) # I expect DictyThing! Any thoughts? -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I use __setitem__ method of dict object?
On Feb 6, 10:59 am, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On 6 fév, 16:23, "jeremito" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Please excuse me if this is obvious to others, but I can't figure it
> > out. I am subclassing dict, but want to prevent direct changing of
> > some key/value pairs. For this I thought I should override the
> > __setitem__ method as such:
>
> > class xs(dict):
> > """
> > XS is a container object to hold information about cross sections.
> > """
>
> > def __new__(cls, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
> > """
> > """
> > x = {}
> > x['xS'] = xS
> > x['xF'] = xF
> > x['nu'] = nu
> > x['xG'] = xG
> > x['xA'] = x['xG'] + x['xF']
> > x['xT'] = x['xA'] + x['xS']
>
> > return x
>
> replace this with:
> def __init__(self, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
>dict.__init__(
>self,
>xS=xS,
>xF=xF,
>xG=xG,
> nu=nu,
> xA=xG + xF,
> xT=xG + xF + xS
> )
>
> > def __setitem__(self, key, value):
> > """
> > I have overridden this method to prevent setting xT or xA
> > outside the
> > class.
> > """
> > print "I am in __setitem__"
> > if key == 'xT':
> > raise AttributeError(
>
> "Can't change xT. Please change, xF, xS, or xG"
>)
>dict.__setitem__(self, key, value)
>
> > But I can't even get __setitem__ to run.
>
> of course, since your __new__ method returns a dict instance, not a xs
> instance...
> There are very few cases where you really need to override the __new__
> method.
The reason I create my object with __new__ instead of __init__ is
because when I use __init__ when a value is set it calls __setitem__.
This is what I want to happen, but not inside of __init__. Does this
make sense? I'm sure there is a better/more pythonic way to do this,
but I'm unsure of what it is. Can someone show me an example of how
this should work?
>
> > Example:
> > Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
> > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> > Type "help", "copyright", "credits" or "license" for more information.>>>
> > import xs
> > >>> cs = xs.xs()
> > >>> cs
>
> > {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': 3.0}>>>
> > cs['xT'] = 3.1415
> > >>> cs
>
> > {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT':
> > 3.14150002}
>
> > Is this what the __setitem__ method is for?
>
> Yes. But note that you you need to manually call the superclass's
> overriden method - unless you
> really want to replace it with your own, which is obviously not the
> case here...
>
> Note that if someone manually changes the values of xG, xF, or xS, the
> computed values of xA and/or xT
> won't reflect this change. Is that what you want ?
>
Eventually (when I figure out how to use __setitem__) I will change
what happens when xG, xF, or xS are changed so that it also changes xA
and xT.
> Finally, and if I may ask, what is your use-case for subclassing
> dict ? You don't need this to implement a dict-like object,
> and it might be simpler in your case to write an ordinary class, then
> add support for the required subset of the dict interface.
Eventually I am going to add other features to my class (as I have
mentioned) so I can't simply use a dict object.
>
> My 2 cents...
Thanks again,
Jeremy
--
http://mail.python.org/mailman/listinfo/python-list
Re: when will python 2.5 take in mainstream?
On Feb 6, 3:35 pm, [EMAIL PROTECTED] (Aahz) wrote: > Ben Sizer <[EMAIL PROTECTED]> wrote: > > >It would be great if someone could invest some time in trying to fix > >this problem. I don't think I know of any other languages that require > >recompilation of libraries for every minor version increase. > > How do you define "minor version increase"? If you look at the > progression from 2.0 through 2.5, it's pretty clear that each version > doesn't particularly fit "minor version increase" even though each one > only increments by 0.1. I can't say I agree with that. In terms of naming, it's a minor release because the 'major' release number has stayed at 2. In terms of time, it's a minor release because it's only happening about once every 18 months or so - a short period in computer language terms. In terms of semantics, I'd argue they are minor releases because generally the changes are just minor additions rather than large revisions; I don't see much in the way of significant language alterations for 2.5 apart from arguably 'unified try/except/finally', nor in 2.4. I don't count addition of new types or modules as 'major'. The language itself is fairly stable; it's just the way that it links to extensions which is pretty fragile. -- Ben Sizer -- http://mail.python.org/mailman/listinfo/python-list
Re: huge amounts of pure Python code broken by Python 2.5?
On Feb 6, 8:40 am, Steven Bethard <[EMAIL PROTECTED]> wrote: > Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: > > > Huge amounts of my pure Python code was broken by Python 2.5. > > Interesting. Could you give a few illustrations of this? (I didn't run > into the same problem at all, so I'm curious.) > > Steve At a guess, the most likely thing to break code in job lots in 2.5 was the change in default coding from latin-1 (or whatever the installation has the default set to) to ascii. This would have a tendency to break most modules that depended on the default source coding. Fortunately, the fix is (not quite trivially) easy - just scan the library and put the right coding comment in the front. John Roth -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I use __setitem__ method of dict object?
"jeremito" <[EMAIL PROTECTED]> escribió en el mensaje
news:[EMAIL PROTECTED]
> Please excuse me if this is obvious to others, but I can't figure it
> out. I am subclassing dict, but want to prevent direct changing of
> some key/value pairs. For this I thought I should override the
> __setitem__ method as such:
>if key == 'xT':
>raise AttributeError("""Can't change xT. Please change,
> xF, xS, or xG""")
Why using a dictionary? I'd use a simple class with properties:
py> class Xs(object): # class names should be Uppercase
... def __init__(self, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
... self.xS = xS
... self.xF = xF
... self.nu = nu
... self.xG = xG
... xA = property(fget=lambda self: self.xG + self.xF)
... xT = property(fget=lambda self: self.xA + self.xS)
...
py> xs = Xs(1.0, 0.95, 0.80, 0.70)
py> print xs.xG
0.8
py> print xs.xA
1.75
py> print xs.xT
2.75
py> xs.xG = 0.5
py> print xs.xA
1.45
py> print xs.xT
2.45
py> xs.xA = 1.5
Traceback (most recent call last):
File "", line 1, in ?
AttributeError: can't set attribute
py> xs.xT = 1.2
Traceback (most recent call last):
File "", line 1, in ?
AttributeError: can't set attribute
py>
--
Gabriel Genellina
--
http://mail.python.org/mailman/listinfo/python-list
Re: huge amounts of pure Python code broken by Python 2.5?
"John Roth" <[EMAIL PROTECTED]> escribió en el mensaje news:[EMAIL PROTECTED] > On Feb 6, 8:40 am, Steven Bethard <[EMAIL PROTECTED]> wrote: >> Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: >> >> > Huge amounts of my pure Python code was broken by Python 2.5. >> >> Interesting. Could you give a few illustrations of this? (I didn't run >> into the same problem at all, so I'm curious.) >> > > At a guess, the most likely thing to break code in job lots in 2.5 was > the change in default coding from latin-1 (or whatever the > installation has the default set to) to ascii. And that has given a warning since 2.3... -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Module problem
Hi I am writing some simple script, and when I start my script from command line (python Imenik.py), everything works perfectly. If I double clik the same script in my desktop I get the following error: "No module name import win32clipboard" -- "A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa silovana" -- http://mail.python.org/mailman/listinfo/python-list
Re: Python cheatsheets
Bart Ogryczak wrote: > On Jan 7, 10:03 pm, gonzlobo <[EMAIL PROTECTED]> wrote: >> Curious if anyone has a python cheatsheet* published? I'm looking for >> something that summarizes all commands/functions/attributes. Having >> these printed on a 8" x 11" double-sided laminated paper is pretty >> cool. >> >> * cheatsheet probably isn't the right word, but you get the idea. :) > > http://www.onlamp.com/python/excerpt/PythonPocketRef/ If you have a good color printer, try PQRC http://www.limsi.fr/Individu/pointal/python/pqrc/ But... it use more than a double-sided 8" x 11"... -- http://mail.python.org/mailman/listinfo/python-list
Re: when will python 2.5 take in mainstream?
On 6 Feb 2007 08:46:29 -0800, Ben Sizer <[EMAIL PROTECTED]> wrote: > On Feb 6, 3:35 pm, [EMAIL PROTECTED] (Aahz) wrote: > > Ben Sizer <[EMAIL PROTECTED]> wrote: > > > > >It would be great if someone could invest some time in trying to fix > > >this problem. I don't think I know of any other languages that require > > >recompilation of libraries for every minor version increase. > > > > How do you define "minor version increase"? If you look at the > > progression from 2.0 through 2.5, it's pretty clear that each version > > doesn't particularly fit "minor version increase" even though each one > > only increments by 0.1. > > I can't say I agree with that. In terms of naming, it's a minor > release because the 'major' release number has stayed at 2. In terms > of time, it's a minor release because it's only happening about once > every 18 months or so - a short period in computer language terms. In > terms of semantics, I'd argue they are minor releases because > generally the changes are just minor additions rather than large > revisions; I don't see much in the way of significant language > alterations for 2.5 apart from arguably 'unified try/except/finally', > nor in 2.4. I don't count addition of new types or modules as 'major'. > The language itself is fairly stable; it's just the way that it links > to extensions which is pretty fragile. > > -- > Ben Sizer > You're claiming that it's a minor increase because you didn't see anything that "justifies" a major release. Well, the ABI changed, so there you go. It doesn't really matter what you call it - the Python releases are numbered according to their own rules, and if you disagree you can call 2.5 a major release all you want. Or you can call it a minor release and accept that the ABI changes between minor releases. But making up your own release rules and arguing from those is pretty much a non-starter. -- http://mail.python.org/mailman/listinfo/python-list
Re: Module problem
On Feb 6, 9:29 am, Boris Ozegovic <[EMAIL PROTECTED]> wrote: > Hi > > I am writing some simple script, and when I start my script from command > line (python Imenik.py), everything works perfectly. If I double clik the > same script in my desktop I get the following error: > > "No module name import win32clipboard" > > -- > "A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa > silovana" Do you have more than one version of Python installed? Is win32clipboard installed for both versions? It could be that the python in your PATH variable, used when calling from the command line, is different from the association in the registry. To see the association in the registry use: "reg query HKEY_CLASSES_ROOT \Python.File\shell\open\command" on the command line. Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: huge amounts of pure Python code broken by Python 2.5?
Steven Bethard wrote: > Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: > > Huge amounts of my pure Python code was broken by Python 2.5. > > Interesting. Could you give a few illustrations of this? (I didn't run > into the same problem at all, so I'm curious.) > > Steve I'd like to know, too. I have the same code running in 2.4 and 2.5, and I've had the following problems: 1. Bug [ 1651995 ] sgmllib _convert_ref UnicodeDecodeError exception, new in 2.5 (a patch to sgmllib._convert_ref appears to have broken something) (This might be the switch from Latin-1 to ascii as default, now that I think about it.) 2. MySQLdb isn't fully supported for Python 2.5 yet, and there's no tested Windows executable available, although there's an untested version from a World of Warcraft guild available. 3. M2Crypto has versioning issues between Python, SWIG, gcc, and OpenSSL, and getting everything to play together can be difficult. This is a packaging issue; major Linux distros aren't shipping a compatible set of components. But my own pure Python code is working fine in both version of Python, and on both Windows and Linux. John Nagle -- http://mail.python.org/mailman/listinfo/python-list
Testing a website with HTTPS login and cookies
Did you ever get a response to your posting on "Testing a website with HTTPS login and cookies"? The reason I ask is that I need to do a similar thing, and am not being very successful getting pointers or sample code. Any response appreciated. /mike -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling J from Python
Gosi a écrit : > On Feb 6, 3:04 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > >>On Feb 5, 8:48 am, "Gosi" <[EMAIL PROTECTED]> wrote: >> >> >>>It is quite easy to call J from Python >> >>>http://groups.google.com/group/J-Programming/browse_thread/thread/5e8... >> >>There are a couple of issue that should be adressed. Am I going to >>jail if I write a program and then redistribute all the files required >>to run the program I write?? > > > J is free for anyone to download and use. But not to inspect or modify. This is "free" as in "free beer", not as in "free speech". > >>The second is how do I use the j stuff >>without learning all that much about j. > > > Just like Python then how much time you spend is uo to you. > > If you want to be good at it you may have to spend some time. > > You may also be just a casual user and dip into it now and again. This is easy with Python, which emphasis readability. I doubt one can say the same about j. -- http://mail.python.org/mailman/listinfo/python-list
Re: Module problem
Matimus wrote: > Do you have more than one version of Python installed? Is > win32clipboard installed for both versions? It could be that the Yup, that was the problem. Thanx! -- "A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa silovana" -- http://mail.python.org/mailman/listinfo/python-list
Re: huge amounts of pure Python code broken by Python 2.5?
John> MySQLdb isn't fully supported for Python 2.5 yet, and there's no John> tested Windows executable available, although there's an untested John> version from a World of Warcraft guild available. As Andy Dustman has pointed out a number of times, he doesn't do Windows. Someone in the MySQLdb community who does use Windows is going to have to fill that void. Skip -- http://mail.python.org/mailman/listinfo/python-list
Help with multiple key sort
gurus: I want to implement a sql-like sort-by on multiple keys. I've seen many examples of just two keys. I have a list like this 1 one 2 1 one 1 1 two 1 1 one 0 1 xx 0 result should be like this 1 four 2 1 one 0 1 one 1 1 one 2 1 xx 0 It moves right while keeping sorted order to the left. This is the new stable sort in 2.5. I'm not sure what I'm doing wrong. please help. Thanks -- http://mail.python.org/mailman/listinfo/python-list
electronics and python
Hi guys.Is there any software written using python for electronics.i mean any simulation software or something?? -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with multiple key sort
[EMAIL PROTECTED] writes: > It moves right while keeping sorted order to the left. This is the > new stable sort in 2.5. >>> b ['1 one 2', '1 one 1', '1 two 1', '1 one 0', '1 xx 0'] >>> sorted(b,key=lambda x: x.split()) ['1 one 0', '1 one 1', '1 one 2', '1 two 1', '1 xx 0'] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to prevent from race conditions to share data between many process and thread in python
En Tue, 06 Feb 2007 08:49:51 -0300, Diez B. Roggisch <[EMAIL PROTECTED]> escribió: > mars wrote: > >> On 2月6日, 下午6时14分, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: >>> mars wrote: >>> > I use TurboGears to do some web service. TurboGears use cherrypy. >>> When >>> > web browser access this site, the cherrypy will call my python >>> > program. So my program looks like a lib. When web browser access the >>> > site, the http server will fock a process or gerenate a thread. I >>> need >>> > share some data or operate some files. How can I prevent from race >>> > conditions. Is there any way can I lock this. >>> > Thank you in advance! >>> >>> There are the Lock and RLock objects available in the module threading. >> >> Can this also lock mutil-process? > > No. You have to use the syncronization tools provided by your OS in that case; maybe using a locked file (fcntl). -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I access data from MS Access?
On 5 Feb, 19:40, "Sells, Fred" <[EMAIL PROTECTED]> wrote: > Years ago we used to get our FORTRAN card decks back from the DP center > with a piece of scrap paper saysing "She No Work". top that. I used to use a cross-compiler (targetting some obscure single-chip hardware) that had just a single error message "Diddley-squat somewhere near here" -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with multiple key sort
[EMAIL PROTECTED] kirjoitti: > gurus: > > I want to implement a sql-like sort-by on multiple keys. I've seen > many examples of just two keys. > > I have a list like this > > 1 one 2 > 1 one 1 > 1 two 1 > 1 one 0 > 1 xx 0 > > result should be like this > > 1 four 2 > 1 one 0 > 1 one 1 > 1 one 2 > 1 xx 0 > > It moves right while keeping sorted order to the left. This is the > new stable sort in 2.5. > > I'm not sure what I'm doing wrong. please help. > > Thanks > I'm not a guru. Maybe that's why I don't understand which "sql-like sort-by on multiple keys" would produce output that lacks some of the input but has additional items. ;) In other words: why don't you show your concrete program and the input and output data to use. Is the data a list of tuples or lists or what? Cheers, Jussi -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with multiple key sort
Paul already answered it. Tnx Paul. My data is in a file and now I have to take care to strip \t and \n from it. Thanks > I'm not a guru. Maybe that's why I don't understand which "sql-like > sort-by on multiple keys" would produce output that lacks some of the > input but has additional items. ;) > > In other words: why don't you show your concrete program and the input > and output data to use. Is the data a list of tuples or lists or what? > > Cheers, > Jussi -- http://mail.python.org/mailman/listinfo/python-list
Re: Repr or Str ?
In article <[EMAIL PROTECTED]>, "Johny" <[EMAIL PROTECTED]> wrote: > Where and when is good/nescessary to use `repr` instead of `str` ? > Can you please explain the differences You expect repr to include information that you might call `meta-data' or `type' -- object class and so forth. To the extent that this is of any interest, it's more or less equally of interest with all objects. If you go to the trouble to support str separately, it's a data conversion and of course should render only the data. An application should be able to use str() to force data to string type (that's what I mean by conversion.) If the object can't sensibly be converted to string type, then normally __str__ is omitted, and defaults to __repr__. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I access data from MS Access?
On Feb 5, 4:52 am, "Andy Dingley" <[EMAIL PROTECTED]> wrote: > On 3 Feb, 15:43, [EMAIL PROTECTED] wrote: > > > How to access data from MS Access? > > First of all check that the DSN is working and connects to the > back end MDB. This might not be Python's problem. > > Secondly check whatever errors you're being returned. Yes, and then move onto something like this: http://www.freelance-developer.com/howto_odbcpy rd "Give a man a fire and keep him warm for a day. Light a man on fire and he will be warm for rest of his life." --Terry Pratchett -- http://mail.python.org/mailman/listinfo/python-list
Re: XMLRPC Server
Brian Quinlan wrote: > Actually, you might not have to. 2000 calls/minute isn't that big, > assuming you have a decent server. well, if you're talking pure CGI, you need to start the interpreter, import the required modules, connect to the database, unmarshal the xml-rpc request, talk to the database, marshal the response, and shut down, in less than 30 milliseconds. just importing the CGI module (or the database module) can take longer than that... -- http://mail.python.org/mailman/listinfo/python-list
Re: huge amounts of pure Python code broken by Python 2.5?
On Tue, 06 Feb 2007 08:40:40 -0700, Steven Bethard <[EMAIL PROTECTED]> wrote: >Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: > > Huge amounts of my pure Python code was broken by Python 2.5. > >Interesting. Could you give a few illustrations of this? (I didn't run >into the same problem at all, so I'm curious.) > There are about half a dozen examples linked from here: http://twistedmatrix.com/trac/ticket/1867 Check out the closed ticket linked from there or the changesets for more detail. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: How can I use __setitem__ method of dict object?
jeremito a écrit : > On Feb 6, 10:59 am, "[EMAIL PROTECTED]" > <[EMAIL PROTECTED]> wrote: > >>On 6 fév, 16:23, "jeremito" <[EMAIL PROTECTED]> wrote: >> (snip) >>>But I can't even get __setitem__ to run. >> >>of course, since your __new__ method returns a dict instance, not a xs >>instance... >>There are very few cases where you really need to override the __new__ >>method. > > > The reason I create my object with __new__ instead of __init__ is > because when I use __init__ when a value is set it calls __setitem__. > This is what I want to happen, but not inside of __init__. Does this > make sense? It would make sens - if you couldn't call dict.__setitem__ directly. > I'm sure there is a better/more pythonic way to do this, > but I'm unsure of what it is. Can someone show me an example of how > this should work? > > (snip) >>>Is this what the __setitem__ method is for? >> >>Yes. But note that you you need to manually call the superclass's >>overriden method - unless you >>really want to replace it with your own, which is obviously not the >>case here... >> >>Note that if someone manually changes the values of xG, xF, or xS, the >>computed values of xA and/or xT >>won't reflect this change. Is that what you want ? >> > > > Eventually (when I figure out how to use __setitem__) I will change > what happens when xG, xF, or xS are changed so that it also changes xA > and xT. Which is not the best way to go IMHO. Unless the computation is very intensive (which doesn't seem to be the case here) or it's heavily used in big loops *and* the perfs are not good enough, it's better to recompute on the fly at read time. And if one of the above cases arises, then it will be time to use memoization (ie: cache the result of computation, invalidating the cache when needed). > >>Finally, and if I may ask, what is your use-case for subclassing >>dict ? You don't need this to implement a dict-like object, >>and it might be simpler in your case to write an ordinary class, then >>add support for the required subset of the dict interface. > > > Eventually I am going to add other features to my class (as I have > mentioned) so I can't simply use a dict object. I already understood this. My question is : why do you want to *subclass* dict. In Python, inheritence is only about implementation, it's *not* needed for polymorphism to work. So you don't have to subclass dict to have an object behaving (more or less, that's up to you) like a dict. Here's an alternative implementation, so you get the idea. Note that it behaves mostly like a dict (well, not totally, but since we don't know which subset of the dict interface you need...), but also like a 'standard' object, so you can use either cs.['xT'] or cs.xT with the same result. class Xs(dict): """ Xs is a container object to hold information about cross sections. """ _computedkeys = 'xA', 'xT' def __init__(self, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0): self.xS = xS self.xF = xF self.xG = xG self.nu = nu # xA and xT as properties (AKA computed attributes) def _get_xA(self): return self.xG + self.xF def _set_xA(self, dummy): raise AttributeError( "%s.xA is read-only" % self.__class__.__name__ ) xA = property(fset=_set_xA, fget=_get_xA) def _get_xT(self): return self.xA + self.xS def _set_xT(self, dummy): raise AttributeError( "%s.xT is read-only" % self.__class__.__name__ ) xT = property(fset=_set_xT, fget=_get_xT) # dict interface support, to be extended if needed def __setitem__(self, key, value): setattr(self, key, value) def __getitem__(self, key): return getattr(self, key) def keys(self): return self.__dict__.keys() + list(self._computedkeys) def values(self): return self.__dict__.values() \ + [getattr(self, key) for key in self._computedkeys] def items(self): return zip(self.keys(), self.values()) def __iter__(self): for k in self.keys(): yield k raise StopIteration def __contains__(self, key): return key in self.keys() def __repr__(self): return repr(dict(self.items())) -- http://mail.python.org/mailman/listinfo/python-list
Re: Running long script in the background
[EMAIL PROTECTED] wrote: > I tried flushing stdout and the same thing happens. As soon as the > os.popen(command) line runs it stops there, the next print statement > never even runs. > > I've also tried using os.spawnv to make the process run in the > background but then the ssh command never runs. Based on what you describe, this isn't a good application for a single-transaction CGI exchange. The timeouts are not happening at the level of your CGI script, but rather either at the HTTP server itself or at the remote client. In either case, fixing it as a one-transaction, one-script solution is not going to be very feasible. A more sensible way to do it is to have one logical page (which could be the same physical page if you want) which accepts job requests, spawns them off in the background, and offers a link to a second logical page which sees if the job has completed -- showing the results if it has -- or refreshes periodically if it hasn't yet. -- Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis You could have another fate / You could be in another place -- Anggun -- http://mail.python.org/mailman/listinfo/python-list
Re: Running long script in the background
On Feb 6, 2:02 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: > On 6 Feb 2007 07:37:33 -0800, "[EMAIL PROTECTED]" > <[EMAIL PROTECTED]> declaimed the following in comp.lang.python: > > > > > Everything works fine until I call the popen function, then it > > freezes. What I want is to print the output in real time, just like > > it does when I run it from a shell. > > And you want /this/ in a web page? > > I don't think HTTP is designed for that... As I understand it, it > expects to get a complete page back and then the transaction is complete > and forgotten (except for the presence of session cookies). To report > dynamically on a web page tends to either be something like a > timed-redirect (reload) of the same URL with the cookie, and that is a > completely separate transaction starting a new CGI (or equivalent) > process. AJAX techniques may clean up some of this -- by not really > reloading the whole page, instead updating the DOM based upon data > transferred. Web pages can show output as it's sent. For testing I created a script on the server that untars a 600 meg volume, I can see each file name show up in my browser instantly, just like it should. The other script I'm trying to run won't show anything until the entire process is complete and it's just a bunch of echo statements in a for loop, I'm not sure why they behave differently. -- http://mail.python.org/mailman/listinfo/python-list
Re: Running long script in the background
[EMAIL PROTECTED] wrote: > Web pages can show output as it's sent. For testing I created a > script on the server that untars a 600 meg volume, I can see each file > name show up in my browser instantly, just like it should. The other > script I'm trying to run won't show anything until the entire process > is complete and it's just a bunch of echo statements in a for loop, > I'm not sure why they behave differently. In a word: buffering. -- Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis You could have another fate / You could be in another place -- Anggun -- http://mail.python.org/mailman/listinfo/python-list
Trouble fixing a broken ASCII string - "replace" mode in codec not working.
I'm trying to clean up a bad ASCII string, one read from a
web page that is supposedly in the ASCII character set but has some
characters above 127. And I get this:
File "D:\projects\sitetruth\InfoSitePage.py", line 285, in httpfetch
sitetext = sitetext.encode('ascii','replace') # force to clean ASCII
UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 29151:
ordinal not in range(128)
Why is that exception being raised when the codec was told 'replace'?
(And no, just converting it to Unicode with "sitetext = unicode(sitetext)"
won't work either; that correctly raises a Unicode conversion exception.)
[Python 2.4, Win32]
JohnNagle
--
http://mail.python.org/mailman/listinfo/python-list
Re: electronics and python
lee wrote: >Hi guys.Is there any software written using python for >electronics.i mean any simulation software or something?? > > Here's 'something': http://home.tiscali.be/be052320/Unum.html I find it useful for basic electronics math (Ohm's law, filters, etc). It keeps track of the units for you and does the right thing when you divide and multiply. You might find this recipie useful in combination with Unum: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499350 I'm not aware of anything else in the Python world that fits your query. Wish I was... HTH, Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: XMLRPC Server
Fredrik Lundh wrote: > well, if you're talking pure CGI, you need to start the interpreter, > import the required modules, connect to the database, unmarshal the > xml-rpc request, talk to the database, marshal the response, and shut > down, in less than 30 milliseconds. > > just importing the CGI module (or the database module) can take longer > than that... The original performance specification was "...receive up to 2000 calls per minute". I don't believe that means that a call has to be serviced in under 30ms (wall-clock time) but total CPU time would have to be <30ms in order to not fall behind under a constant 2000 requests/second load. So we can probably remove database connection and communication time (i.e. IO-bound components). Still, it's a lot tighter than I though it would be: % time python -c "import SimpleXMLRPCServer; import MySQLdb" real 0m0.144s user 0m0.046s sys 0m0.064s So it's already almost 4x too slow. But I'm running this on Ubuntu, running on VMWare on my 1.6GHz Pentium-M laptop. I would assume that a beefy server would do a lot better. Cheers, Brian -- http://mail.python.org/mailman/listinfo/python-list
Re: Trouble fixing a broken ASCII string - "replace" mode in codec not working.
John Nagle wrote:
> I'm trying to clean up a bad ASCII string, one read from a
> web page that is supposedly in the ASCII character set but has some
> characters above 127. And I get this:
>
> File "D:\projects\sitetruth\InfoSitePage.py", line 285, in httpfetch
> sitetext = sitetext.encode('ascii','replace') # force to clean ASCII
>
> UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 29151:
> ordinal not in range(128)
>
> Why is that exception being raised when the codec was told 'replace'?
The .encode('ascii') takes unicode strings to str strings. Since you gave it a
str string, it first tried to convert it to a unicode string using the default
codec ('ascii'), just as if you were to have done
unicode(sitetext).encode('ascii', 'replace').
I think you want something like this:
sitetext = sitetext.decode('ascii', 'replace').encode('ascii', 'replace')
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python cheatsheets
> If you have a good color printer, try > PQRChttp://www.limsi.fr/Individu/pointal/python/pqrc/ That is a very usefull document to use besides Richard Gruets quick ref. The only disadvantage is that it's a PDF document, pity there's no HTML version. 2B -- http://mail.python.org/mailman/listinfo/python-list
Re: Recursive zipping of Directories in Windows
On Feb 6, 1:48 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote: > On Feb 4, 12:42 pm, "Jandre" <[EMAIL PROTECTED]> wrote: > > > > > On Feb 1, 9:39 pm, Larry Bates <[EMAIL PROTECTED]> wrote: > > > > Jandre wrote: > > > > Hi > > > > > I am a python novice and I am trying to write a python script (most of > > > > the code is borrowed) to Zip a directory containing some other > > > > directories and files. The script zips all the files fine but when it > > > > tries to zip one of the directories it fails with the following > > > > error: > > > > "IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'" > > > > > The script I am using is: > > > > > import zipfile, os > > > > > def toZip( directory, zipFile ): > > > > """Sample for storing directory to a ZipFile""" > > > > z = zipfile.ZipFile( > > > > zipFile, 'w', compression=zipfile.ZIP_DEFLATED > > > > ) > > > > def walker( zip, directory, files, root=directory ): > > > > for file in files: > > > > file = os.path.join( directory, file ) > > > > # yes, the +1 is hacky... > > > > archiveName = file[len(os.path.commonprefix( (root, > > > > file) ))+1:] > > > > zip.write( file, archiveName, zipfile.ZIP_DEFLATED ) > > > > print file > > > > os.path.walk( directory, walker, z ) > > > > z.close() > > > > return zipFile > > > > > if __name__ == "__main__": > > > > toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' ) > > > > > I have tried to set the permissions on the folder, but when I check > > > > the directory permissions it is set back to "Read Only" > > > > > Any suggestions? > > > > > Thanks > > > > Johan Balt > > > > Couple of quick suggestions that may help: > > > > 1) don't use 'file' as a variable name. It will mask > > > the builtin file function. If it hasn't bitten you before > > > it will if you keep doing that. > > > > 2) If you put the target .zip file in the directory you are > > > backing what do you expect the program to do when it comes > > > to the file you are creating as you walk the directory? You > > > haven't done anything to 'skip' it. > > > > 3) Your commonprefix and +1 appears to result in same > > > information that the easier to use os.path.basename() > > > would give you. Double check me on that. > > > > I don't see anything that references C:\\aaa\temp in your > > > code. Does it exist on your hard drive? If so does it > > > maybe contain temp files that are open? zipfile module > > > can't handle open files. You must use try/except to > > > catch these errors. > > > > Hope info helps. > > > > -Larry > > > Thank you Larry. > > I've changed the code as epr your advice. The code is now: > > > import zipfile, os > > > def toZip( directory, zipFile ): > > """Sample for storing directory to a ZipFile""" > > z = zipfile.ZipFile( > > zipFile, 'w', compression=zipfile.ZIP_DEFLATED > > ) > > def walker( zip, directory, files, root=directory ): > > for f in files: > > f = os.path.join( directory, f ) > > archiveName = os.path.basename(f) > > zip.write( f, archiveName, zipfile.ZIP_DEFLATED ) > > print f > > os.path.walk( directory, walker, z ) > > z.close() > > return zipFile > > > if __name__ == "__main__": > > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' ) > > > I still get the same error: > > Traceback (most recent call last): > > File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework > > \scriptutils.py", line 310, in RunScript > > exec codeObject in __main__.__dict__ > > File "C:\Python24\Scripts\dirZip.py", line 20, in ? > > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' ) > > File "C:\Python24\Scripts\dirZip.py", line 14, in toZip > > os.path.walk( directory, walker, z ) > > File "C:\Python24\lib\ntpath.py", line 329, in walk > > func(arg, top, names) > > File "C:\Python24\Scripts\dirZip.py", line 12, in walker > > zip.write( f, archiveName, zipfile.ZIP_DEFLATED ) > > File "C:\Python24\lib\zipfile.py", line 405, in write > > fp = open(filename, "rb") > > IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp' > > > c:\\aaa\\temp is a directory in the directory I an trying to zip. I > > want to use this script to back up my work once a day and would like > > to > > keep the directory structure as is. I can zip the files in c:\aaa\tem > > fine so I guess that there aren't any open files in the directory. > > Any more ideas? > > Hi Jandre, > > Your code is treating the directory as a file and trying to open it > and read its bytes to zip them. You'll need to differentiate between > files and directories. > > You'll need to check out the Zip module to see how it expects files > that should be nested within folders. I believe you'll need to set the > archive name for the nested files to something like \\temp\\file.ext > etc. > In my experience, zip files don't contain nested folders, instead they contain a 'flat' l
Python editor
No, no, no, this is not an invitation to the editor wars. I have been using José Cláudio Faria's superb Tinn-R, http://www.sciviews.org/Tinn-R/, with the R language, http://www.r-project.org/. This editor allows you to send code to the R shell for execution. You can easily send a line, the selection, the balance after the cursor or the whole script. I have recently decided to move this project to Python instead of R. However, I miss the interaction with the shell a la Tinn-R. Do any of the Python editors support this feature? I would be especially interested in using IPython as the shell. jab -- http://mail.python.org/mailman/listinfo/python-list
Re: electronics and python
On Feb 6, 1:38 pm, "lee" <[EMAIL PROTECTED]> wrote: > Hi guys.Is there any software written using python for > electronics.i mean any simulation software or something?? There's MyHDL. http://myhdl.jandecaluwe.com/doku.php I found it originally in a Linux Journal article some years ago. http://www.linuxjournal.com/article/7542 Haven't tried it in a while so you'll have to test it yourself. -- http://mail.python.org/mailman/listinfo/python-list
Re: electronics and python
lee wrote: > Hi guys.Is there any software written using python for > electronics.i mean any simulation software or something?? > There are a few starts, (I can't find my notes right now, so from my head) - there's a 68c11 simulator - there's a spice implementation or at least a good coupling - the most promising combination is Python+Modelica, some seem to have it workin - and there's another one, can't remember as an exercise I tried to build a PIC simulator, works, but it is slow. cheers, Stef Mientki -- http://mail.python.org/mailman/listinfo/python-list
Re: Two mappings inverse to each other: f, g = biject()
Jonathan Fine: > A google search for biject.py and bijection.py > produced no hits, so I suspect that this may not > have been done before. There are few (good too) implementations around, but they are called bidict or bidirectional dicts. Sometimes I use this implementation, with few changes: http://www.radlogic.com.au/releases/two_way_dict.py Bye, bearophile -- http://mail.python.org/mailman/listinfo/python-list
