python module developer wanted for 'libmsgque'
Hi, I'm a the maintainer for the new project 'libmsgque' hosted at SF (see below for details) and need a volunteer to develop the language bindings for python. Is somebody available to take over this job ? An example language binding for tcl is allready available. This is the initial announcement: ANNOUNCE: libmsgque2.3-beta2 The libmsgque project is an infrastructure for linking applications together to act like a single application. This is done using Unix or inet domain sockets. The framework handles all aspects of setting up and maintaining the link in addition to starting and stopping the different applications, starting and stopping the communication interface, sending and receiving packages, reading and writing data from or into packages, setting up and maintaining the event handling for asynchronous transfers, and propagating warnings or errors. WHERE TO GET As usual, it is available from: http://libmsgque.sourceforge.net/ http://sourceforge.net/projects/libmsgque/ WHAT'S NEW == This is the initial announcement WHAT IS IT == First of all it is a framework to link commands together to avoid the traditional shell pipline using a similar approach as MS PowerShell. To get more information's please use the following links: 1. an overview about the basic concept: http://libmsgque.sourceforge.net/overview.htm 2. the man page of the tclmsgque extension: http://libmsgque.sourceforge.net/tclmsgque.htm Regards, Andreas Otto (aotto1968) -- http://mail.python.org/mailman/listinfo/python-list
Re: Erlang style processes for Python
On May 10, 8:31 am, Jacob Lee <[EMAIL PROTECTED]> wrote: > Funny enough, I'm working on a project right now that is designed for > exactly that: PARLEY,http://osl.cs.uiuc.edu/parley. (An announcement > should show up in clp-announce as soon as the moderators release it). My > essential thesis is that syntactic sugar should not be necessary -- that a > nice library would be sufficient. Synsugar is helpfull when you want to control compiler actions. Of course you can do this also by means of __special__ attributes but I guess this becomes clutter when you work with certain exposed sections in the code. > I do admit that Erlang's pattern > matching would be nice, although you can get pretty far by using uniform > message formats that can easily be dispatched on -- the tuple > (tag, sender, args, kwargs) > in the case of PARLEY, which maps nicely to instance methods of a > dispatcher class. Yes, I do think so too. It is more interesting to think about what might be qualify as a message. Destructuring it is not hard in anyway and I do also have a few concerns with naive pattern matching: http://www.fiber-space.de/EasyExtend/doc/gallery/gallery.html#4._Chainlets_and_the_switch-statement > The questions of sharing among multiple physical processes is interesting. > Implicit distribution of actors may not even be necessary if it is easy > enough for two hosts to coordinate with each other. In terms of the > general question of assigning actors to tasklets, threads, and processes, > there are added complications in terms of the physical limitations of > Python and Stackless Python: > - because of the GIL, actors in the same process do not gain the > advantag of true parallel computation > - all tasklet I/O has to be non-blocking > - tasklets are cooperative, while threads are preemptive > - communication across processes is slower, has to be serialized, etc. > - using both threads and tasklets in a single process is tricky Actors don't need locking primitives since their data is locked by virtue of the actors definition. That's also why I'm in favour for a runtime / compiler based solution. Within the shiny world of actors and actresses the GIL has no place. So a thread that runs actors only, does not need to be blocked or block other threads - at least not for data locking purposes. It is used much like an OS level process with better sharing capabilities ( for mailbox addresses and messages ). Those threads shall not take part of the access/release GIL game. They might also not be triggered explicitely using the usual threading API. > PARLEY currently only works within a single process, though one can choose > to use either tasklets or threads. My next goal is to figure out I/O, at > which point I get to tackle the fun question of distribution. > > So far, I've not run into any cases where I've wanted to change the > interpreter, though I'd be interested in hearing ideas in this direction > (especially with PyPy as such a tantalizing platform!). > -- > Jacob Lee <[EMAIL PROTECTED]> I guess you mean tantalizing in both of its meanings ;) Good luck and inform us when you find interesting results. Kay -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter - Screen Resolution
On Wed, 09 May 2007 18:37:32 +0200, <[EMAIL PROTECTED]> wrote: > Hi, > I have developed a GUI using tkinter (grid geometory manager). > The structure is a top frame containing multiple subframes. Each > subframe has a combination of widgets like(Entry, label, > button,listboxes). The subframes are placed with a padx and pady > offset with regards to the other subframes. And the widgets within > these subframes have their own padx and pady offsets. The GUI runs > fine on my linux box, but on a different linux box things get wierd. > I see things like- > 1) The frame width increasing > 2) The widget padx translating to much bigger offsets with reference > to the subframe edges > 3) Widget widths like that for Entry become bigger > > I Know its to do with the screen resolution settings and user settings > on different machines. Can anyone point me in the right > direction(before I start looking into it)as how to account for > different screen resolutions so as to have as uniform a GUI look as > possible across different user machines. [snip] For some reason, tk uses different default units for coordinates and font sizes: a coordinate specified as just a number is considered to be in pixels (a.k.a screen points); a font size specified as just a number is considered to be in points, i.e 1/72 inch. So these units are the same only if your screen resolution is exactly 72 dpi, which is usually not the case. If this is actually your problem, the way to correct it is quite simple: the tk command "tk scaling 1" tells tk that a point and a pixel are the same thing. To issue it, you may have to use explicitely the tcl interpreter used by Tkinter by doing: aWidget.tk.call('tk', 'scaling', 1) where aWidget is any Tkinter widget. This is what I had to do with Python 2.1; it may be easier with later Python/Tkinter versions. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing dates problem
[EMAIL PROTECTED] wrote: > I am writing a reminder program for our Zimbra email client. One of > the requirements I was given was to automatically increment or > decrement the display to show something like the following: > > 5 minutes until appointment > > or > > 10 minutes past your appointment > > > Either way, as each minute goes by, I need to increment it or > decrement it. I am having trouble finding a coherent way to take the > same date and compare just the number of minutes between them to find > the difference. Like if I have an appointment at 9:30 a.m. and the app > is loaded at 8 a.m., I need to know the number of minutes or hours and > minutes until the appointment. Not the most elegant piece of code on earth, but this piece of code works for me (cut-and-pasted directly from a working project, so doesn't *exactly* match your requirement). def deltastamp (now, then): def pluralise (base, n): if n > 1: return "%d %ss" % (n, base) else: return "%d %s" % (n, base) if now > then: output_format = "%s ago" delta = now - then else: output_format = "in %s" delta = then - now days = delta.days if days <> 0: wks, days = divmod (days, 7) if wks > 0: output = pluralise ("wk", wks) else: output = pluralise ("day", days) else: mins, secs = divmod (delta.seconds, 60) hrs, mins = divmod (mins, 60) if hrs > 0: output = pluralise ("hr", hrs) elif mins > 0: output = pluralise ("min", mins) else: output = pluralise ("sec", secs) return output_format % output TJG -- http://mail.python.org/mailman/listinfo/python-list
the inspect thing
-the code: class A: b=2 import inspect print inspect.getsource(A) class A: c=2 print inspect.getsource(A) -unavailable from the console, but gets you: class A: b=2 class A: b=2 One thought is, in inspect, could at least: def findsource(object): #snip if candidates: # this will sort by whitespace, and by line number, # less whitespace first candidates.sort() return lines, candidates[0][1] be return lines, candidates[-1][1] to get the most recent? Why no cl_firstlineno in the object for the class, or access to the code?-acb -- http://mail.python.org/mailman/listinfo/python-list
replacing string in xml file--revisited
Hi, I need to replace a string in xml file with something else.Ex - rate rate - Here i have opened an xml file(small part is pasted here).I want to replace the word 'localId' with 'dataPackageID' wherever it comes in xml file.I have asked this before and got a code: input_file = open(filename) xmlcontents = input_file.read() input_file.close() xmlcontents = xmlcontents.replace("spam", "eggs") output_file = open(filename,"w") output_file.write(xmlcontents) output_file.close() Although this works alone it is nto working when i handle multiple file I/O.Is there a alternative to do this.(maybe without read() operation) Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: preferred windows text editor?
On May 9, 11:21 pm, BartlebyScrivener <[EMAIL PROTECTED]> wrote: ... > I too vote for VIM. I use it on both Windows XP and Debian Etch. I > can't find anything it doesn't do. I also use Vim (well, GVim). The only thing I find missing is an integrated console for running code snippets/entire scripts. The runscript plugin is OK, but lacks interactive use. I have been thinking about some way of interacting with a Python shell using sockets to send snippets directly to the shell from Vim, but haven't had time to get very far. What method of executing code snippets in a Python shell do other Vim users use? Other than just copy/paste? -- http://mail.python.org/mailman/listinfo/python-list
Re: elegant python style for loops
thank you everybodyvery well answered.just one question remains where do i find documentation on zip ...i was looking for a function like this, but could not even find a relevant list of functions!! -- http://mail.python.org/mailman/listinfo/python-list
Re: Erlang style processes for Python
Have you seen Candygram? http://candygram.sourceforge.net/ jon N -- http://mail.python.org/mailman/listinfo/python-list
Re: elegant python style for loops
On May 10, 6:00 pm, [EMAIL PROTECTED] wrote: > thank you everybodyvery well answered.just one question > remains > where do i find documentation on zip ...i was looking for a function > like this, but could not even find a relevant list of functions!! ooops...even that was answered. again, thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Specification for win32com.client package
Hello Tim, thank you for your quick and detailed reply. So I will try it at the python-win32 list. Many thanks for your help and if you want I will let you know when I know more. Best regards, Peter. - Need Mail bonding? Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users.-- http://mail.python.org/mailman/listinfo/python-list
Re: SEO - Search Engine Optimization - Seo Consulting
"Steve Holden" <[EMAIL PROTECTED]> wrote: > Steven D'Aprano wrote: > > On Wed, 02 May 2007 19:47:28 -0700, Huck Phin wrote: > [a request for peace, love and understanding, concluding with] > >> We all should be a little more considerate of each other. > > > > And if the hippy hug fest fails to stop spamming, perhaps we'll be allowed > > to hunt them down like rabid dogs and stick their heads up on pikes as a > > warning to others. > > > > Hey, a man can dream can't he??? *wink* > > > > > Yeah, just ONE day a year when we could roast them on spits over open > fires ... just to discourage the survivors, you understand. > This is a surprisingly violent group of people, judging by the responses elicited in this thread, and in the muzzle velocity one. Better watch my step... - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: elegant python style for loops
On May 10, 6:51 am, [EMAIL PROTECTED] wrote: ... > into a list of tuples to allow moving through multiple lists, or is > the for i in range(len(listkeys)): the only solution? > > Any suggestions? For the specific case of indexing lists, the following is cleaner than the 'for i in range...' solution above, and works in cases where zipping the lists may not be appropriate: for i, item in enumerate(mylist): print "%s) My item: %s; My other item: %s" % (i, item, my_non_iterable_object.thing_at(i)) -- Ant. -- http://mail.python.org/mailman/listinfo/python-list
Re: Towards faster Python implementations - theory
"Terry Reedy" <[EMAIL PROTECTED],,.edu> wrote: > "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] > | I am relatively new on this turf, and from what I have seen so far, it > | would not bother me at all to tie a name's type to its first use, so that > | the name can only be bound to objects of the same type as the type > | of the object that it was originally bound to. > | > | But maybe I am missing the point of dynamism. > | > | Would an implementation of the above break lots of stuff in practice? > > For function local variables, if you mean 'originally bound to' in the > current call invocation, that would sometimes be ok (and that is sort of > what Psycho does). But if you mean in the original binding in the first > call invocation, then that would cripple many functions. > Errr - I was thinking a bit simplistic - I know I can write: def f(x): for y in x: print y# using print here as short for doing something complicated And that would currently "work" with any iterable, as x could currently be anything. It seems that such functions are the problem, as something like this: x = [1,2,3,4,5] for y in x: print y does not have the same hassle for x, but can shift the problem to y: x = [1,2,3,4,(1,2)] for y in x: print y I can't see an easy way to put the patient back into his straight jacket. Makes you want to use pre defined globals... - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Change serial timeout per read
<[EMAIL PROTECTED]> wrote: > I'm writing a driver in Python for an old fashioned piece of serial > equipment. Currently I'm using the USPP serial module. From what I can > see all the serial modules seem to set the timeout when you open a > serial port. This is not what I want to do. I need to change the > timeout each time I do a "read" on the serial port, depending on > which part of the protocol I've got to. Sometimes a return character > is expected within half a second, sometimes within 2 seconds, and > sometimes within 20 seconds. How do I do this in USPP, or Pyserial, or > anything else? Currently I'm working in Windows, but I'd prefer a > platform independent solution if possible... Yikes! you will probably have to make the port non blocking, and roll your own using different time.sleep(n) values between invocations to port.read(1) calls Unless you can afford to close and open the port each time - but that way leads to missed characters... - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Re: Towards faster Python implementations - theory
"John Nagle" <[EMAIL PROTECTED]> wrote: > Paul Boddie wrote: > > On 9 May, 08:09, "Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote: > > > >>I am relatively new on this turf, and from what I have seen so far, it > >>would not bother me at all to tie a name's type to its first use, so that > >>the name can only be bound to objects of the same type as the type > >>of the object that it was originally bound to. > > > > > > But it's interesting to consider the kinds of names you could restrict > > in this manner and what the effects would be. In Python, the only kind > > of name that can be considered difficult to arbitrarily modify "at a > > distance" - in other words, from outside the same scope - are locals, > > and even then there are things like closures and perverse > > implementation-dependent stack hacks which can expose local namespaces > > to modification, although any reasonable "conservative Python" > > implementation would disallow the latter. > > Modifying "at a distance" is exactly what I'm getting at. That's the > killer from an optimizing compiler standpoint. The compiler, or a > maintenance programmer, looks at a block of code, and there doesn't seem > to be anything unusual going on. But, if in some other section of > code, something does a "setattr" to mess with the first block of code, > something unusual can be happening. This is tough on both optimizing > compilers and maintenance programmers. > > Python has that capability mostly because it's free in an > "everything is a dictionary" implementation. ("When all you have > is a hash, everything looks like a dictionary".) But that limits > implementation performance. Most of the time, nobody is using > "setattr" to mess with the internals of a function, class, or > module from far, far away. But the cost for that flexibility is > being paid, unnecessarily. > > I'm suggesting that the potential for "action at a distance" somehow > has to be made more visible. > > One option might be a class "simpleobject", from which other classes > can inherit. ("object" would become a subclass of "simpleobject"). > "simpleobject" classes would have the following restrictions: > > - New fields and functions cannot be introduced from outside > the class. Every field and function name must explicitly appear > at least once in the class definition. Subclassing is still > allowed. > - Unless the class itself uses "getattr" or "setattr" on itself, > no external code can do so. This lets the compiler eliminate the > object's dictionary unless the class itself needs it. > > This lets the compiler see all the field names and assign them fixed slots > in a fixed sized object representation. Basically, this means simple objects > have a C/C++ like internal representation, with the performance that comes > with that representation. > > With this, plus the "Shed Skin" restrictions, plus the array features of > "numarray", it should be possible to get computationally intensive code > written in Python up to C/C++ levels of performance. Yet all the dynamic > machinery of Python remains available if needed. > > All that's necessary is not to surprise the compiler. > If this is all it takes, I would even be happy to have to declare which things could be surprising - some statement like: x can be anything Would that help? It kind of inverts the logic - and states that if you want what is now the default behaviour, you have to ask for it. - Hendrik -- http://mail.python.org/mailman/listinfo/python-list
Newbie (but improving) - Passing a function name with parameters as a parameter
I am trying to time a function's execution, but I get 'TypeError: 'bool' object is not callable' when I try to run it. I suspect it is my calling of 'timeloop' with the function name 'lookup' and its associated variables or it could just be some stupid error on my part. function 'lookups' was working OK Any help will be appreciated. Thanks - Richard ===The offending Code = #!/usr/bin/python def timeloop(dofunction,iters=10): import datetime print "->-> Start of test", "LOOPS=", iters, datetime.datetime.now().ctime() for x in xrange(iters): print x dofunction() print "<-<- End of test", "LOOPS=", iters, datetime.datetime.now().ctime() def lookup(recs,patterns): matchcount = 0 pattcount = 0 for patt in patterns: if matchcount < pattcount: break pattcount += 1 for rec in recs: # print "PATT:", patt, " REC:", rec, " PATTCOUNT=", pattcount if patt in rec: matchcount +=1 break # print"MATCHCOUNT=",matchcount, "PATTCOUNT=", pattcount if matchcount == pattcount: return True else: return False myrecs = ['This is a title for Brian', 'this is detail one for brian', 'this is detail two for brian', 'this is another detail one for brian'] test1 = ['one', 'nomatch'] test2 = ['one', 'two'] test3 = ['title', 'two', 'nomatcheither'] mypatts = test1 timeloop(lookup(myrecs,mypatts), 10) -- http://mail.python.org/mailman/listinfo/python-list
Re: replacing string in xml file--revisited
In <[EMAIL PROTECTED]>, saif.shakeel wrote: > Although this works alone it is nto > working when i handle multiple file I/O.Is there a alternative to do > this.(maybe without read() operation) Why do you want to change the part that *works* instead of fixing the code that doesn't!? Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Newbie Prob : IDLE can't import Tkinter
Hello, I'have just install Python 2.5.1 on Linux and the IDLE doesn't seem to works because it didn't find Tcl/Tk Is there someone to explain how to modify the file "setup.py" to tell the install that Tcl/Tk are at the paht : "/usr/bin/tclsh" and "usr/bin/wish/" ? I have attached to log file of my terminal. Thanks a lot in advance. Romain [EMAIL PROTECTED] : ll total 8212 drwxr-s--- 19 fr18 Dk_pcell 4096 May 3 15:14 ./ drwxr-s---3 fr18 Dk_pcell 4096 May 3 14:01 ../ -rw-r-1 fr18 Dk_pcell77512 May 3 15:15 2007_05_03_1505_python_install.log drwxr-s---5 fr18 Dk_pcell 4096 May 3 10:12 build/ -rw-r-1 fr18 Dk_pcell 336280 May 3 10:09 config.log -rwxr-x---1 fr18 Dk_pcell57416 May 3 10:09 config.status* -rwxr-x---1 fr18 Dk_pcell 637991 Mar 12 11:50 configure* -rw-r-1 fr18 Dk_pcell96904 Mar 12 11:50 configure.in drwxr-s--- 22 fr18 Dk_pcell 4096 Apr 18 05:56 Demo/ drwxr-s--- 24 fr18 Dk_pcell 4096 Apr 18 06:01 Doc/ drwxr-s---2 fr18 Dk_pcell 4096 Apr 18 05:56 Grammar/ drwxr-s---2 fr18 Dk_pcell 8192 Apr 18 05:55 Include/ -rwxr-x---1 fr18 Dk_pcell 7122 Jun 14 2003 install-sh* drwxr-s--- 42 fr18 Dk_pcell20480 May 3 15:14 Lib/ -rw-r-1 fr18 Dk_pcell 3949072 May 3 15:14 libpython2.5.a -rw-r-1 fr18 Dk_pcell13615 Apr 5 06:52 LICENSE drwxr-s--- 11 fr18 Dk_pcell 4096 Apr 18 05:57 Mac/ -rw-r-1 fr18 Dk_pcell38219 May 3 10:09 Makefile -rw-r-1 fr18 Dk_pcell35107 May 3 10:09 Makefile.pre -rw-r-1 fr18 Dk_pcell35070 Dec 8 21:46 Makefile.pre.in drwxr-s---4 fr18 Dk_pcell 4096 Apr 18 05:56 Misc/ drwxr-s---7 fr18 Dk_pcell12288 May 3 15:14 Modules/ drwxr-s---3 fr18 Dk_pcell 8192 May 3 15:14 Objects/ drwxr-s---2 fr18 Dk_pcell 4096 May 3 15:14 Parser/ drwxr-s---8 fr18 Dk_pcell 4096 Apr 18 05:58 PC/ drwxr-s---2 fr18 Dk_pcell 4096 Apr 18 05:55 PCbuild/ drwxr-s---2 fr18 Dk_pcell 4096 Apr 18 06:08 PCbuild8/ -rw-r-1 fr18 Dk_pcell28357 May 3 10:09 pyconfig.h -rw-r-1 fr18 Dk_pcell27049 Oct 27 2006 pyconfig.h.in -rwxr-x---1 fr18 Dk_pcell 2661658 May 3 15:14 python* drwxr-s---2 fr18 Dk_pcell 8192 May 3 15:14 Python/ -rw-r-1 fr18 Dk_pcell77512 May 3 14:51 python_install.log -rw-r-1 fr18 Dk_pcell55678 Apr 5 06:52 README drwxr-s---5 fr18 Dk_pcell 4096 Apr 18 05:58 RISCOS/ -rw-r-1 fr18 Dk_pcell67931 May 3 15:18 setup.py drwxr-s--- 19 fr18 Dk_pcell 4096 Apr 18 05:58 Tools/ [EMAIL PROTECTED] : build/scripts-2.5/idle ** IDLE can't import Tkinter. Your Python may not be configured for Tk. ** [EMAIL PROTECTED] : which wish /usr/bin/wish [EMAIL PROTECTED] : wish % [EMAIL PROTECTED] : which tclsh /usr/bin/tclsh [EMAIL PROTECTED] : tclsh % info tcl 8.3 % exit -- http://mail.python.org/mailman/listinfo/python-list
Re: preferred windows text editor?
I prefer PsPad. If you like Notepad++, PSPad might be a better choice. More intuitive. I've used Notepad++ for a while, I really disliked the fact that every new install my settings XML file would get overwritten, and what does that guy have with Comic sans MS? Every default style is hard coded into the app, to that strange oddly looking style for comments etc. Anyway, I do not want to get too personal. PsPad is very nice, I also use more python-like editors like SPE and UliPad. - Jorgen On 10 May 2007 00:57:52 -0700, Ant <[EMAIL PROTECTED]> wrote: > On May 9, 11:21 pm, BartlebyScrivener <[EMAIL PROTECTED]> wrote: > ... > > I too vote for VIM. I use it on both Windows XP and Debian Etch. I > > can't find anything it doesn't do. > > I also use Vim (well, GVim). > > The only thing I find missing is an integrated console for running > code snippets/entire scripts. The runscript plugin is OK, but lacks > interactive use. I have been thinking about some way of interacting > with a Python shell using sockets to send snippets directly to the > shell from Vim, but haven't had time to get very far. > > What method of executing code snippets in a Python shell do other Vim > users use? Other than just copy/paste? > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
matplotlib problem
I've got a question regarding matplotlib. I use the command: pylab.plot(...) to create a graph. Then, the execution of the code stops after the line: pylab.show() which is off course the last line of my code. My problem is that I have to close the figure window before in order to finish the execution of my code. I'd like to be able to launch my program other times with different parameters without having to close the figure windows before each launch. Just so you know, I'm using TkAgg backend and the SciTE editor. Following the answer I was given in the thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/939fc6c7a9645bd8/f939f2db9da55430?lnk=gst&q=redcic&rnum=1#f939f2db9da55430 I set "interactive : True" in matplotlibrc. I also tried the other things I had been advised to do but I still have the same problem. Any other idea ? Thanks, Cédric -- http://mail.python.org/mailman/listinfo/python-list
Re: Minor bug in tempfile module (possibly __doc__ error)
In <[EMAIL PROTECTED]>, James T. Dennis wrote: > Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote: >> In <[EMAIL PROTECTED]>, James T. Dennis wrote: > >> You can change it by simply assigning to the name: > >> In [15]: tempfile.template = 'spam' > >> In [16]: tempfile.template >> Out[16]: 'spam' > > I know you can change it. But changing it in your namespace > doesn't change the results returned by the functions called > from the module. I'm not changing it in my namespace but in the namespace of the `tempfile` module. > I don't quite understand how this name/variable in > my namespace (__main__) is able to change the value > while the functions in the module still hold the old > value. Default arguments are evaluated *once* when the ``def`` is executed and not at every function call. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
Re: PYDOC replacement. (Was:Sorting attributes by catagory)
On May 10, 1:28 am, Ron Adam <[EMAIL PROTECTED]> wrote: > Nick Vatamaniuc wrote: > > Ron, > > > Consider using epydoc if you can. Epydoc will sort the methods and it > > will also let you use custom CSS style sheets for the final HTML > > output. Check out the documentation of my PyDBTable module. > >http://www.psipy.com/PyDBTable > > > -Nick Vatamaniuc > > Hi Nick, > > I already have sorting and style sheets taken care of. I'm just trying to > get the content of each sub section correct at this point. The overall > frame work is finished. > > I don't think Epydoc can replace the console help() output. The site.py > module imports help(), from pydoc.py. That serves as the consoles > interactive help mode. When you type help() at the console, you are using > pydoc. > > Some of the differences... > > Epydoc > -- > Output formats: > - html files > - graphs (requires Graphviz) I like this! > - pdf files (requires latex) > > * Requires explicitly generating files first. > * Supports file parsing only instead of introspection. > > Epydoc is more of a complete application and has many nice features such as > the graphs and completeness checks, that will make it better than pydoc for > creating more complete pre-generated html documents with less work. > > Pydoc > = > Output formats: > - live interactive console text > - live interactive html with a local html server. > * no files are generated. (just in the browser cache) > * supports custom CSS stylesheets > > (API data output...) > - text > - html page > - html section (for use in templates) > - xml > - reST (not yet, but will be easy to do) > > The reason for having additional output formats is it makes it much easier > to use it as a tool to extract documentation from source code to be > combined with existing more complete documentation. > > I am planning on writing output formatters to return docutils and docbook > data structures as well. With those, you will be able to convert to latex, > pdf, and other formats. The data formats for those are very close to what > I'm using, so this should be easy to do. > > Other side benefits of doing this is that some of the modules in pydoc have > been generalized so that they can be used without pydoc. The html server, > and the document data and formatter classes, can be used independently of > pydoc. > > The overall total size has not increased much, and it is more modular, > maintainable, and extendable. Maintainability is a major concern for any > library module or package. > > Of course it will need to be approved first. ;-) > > Cheers, > Ron Thanks for the info, Ron. I had no idea pydoc was that powerful! -Nick -- http://mail.python.org/mailman/listinfo/python-list
Re: replacing string in xml file--revisited
On May 10, 12:56 am, [EMAIL PROTECTED] wrote: > Hi, > I need to replace a string in xml file with something else.Ex > > - > rate > rate > > > > - > > Here i have opened an xml > file(small part is pasted here).I want to replace the word 'localId' > with 'dataPackageID' wherever it comes in xml file.I have asked this > before and got a code: > input_file = open(filename) > xmlcontents = input_file.read() > input_file.close() > xmlcontents = xmlcontents.replace("spam", "eggs") > output_file = open(filename,"w") > output_file.write(xmlcontents) > output_file.close() > > Although this works alone it is nto > working when i handle multiple file I/O.Is there a alternative to do > this.(maybe without read() operation) > Thanks try this... #!/usr/bin/env python from elementtree import ElementTree as et tree = et.parse("testxml.xml") for t in tree.getiterator("SERVICEPARAMETER"): t.set("Semantics", "localId") tree.write("output.xml") ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Boost python : get the shape of a numpy ndarray in C++ code.
What I'm trying to say here : a numpy array is supposed to have it's shape stored as a tuple. What I want to do is to access this information from my C++ code, in order to do some validity check. So, by looking around in the doc of boost/python/numeric.hpp I was able to do this : void Layer::set_potentials (numeric::array& array) { for (int h=0; hheight; h++){ for (int w=0; wwidth; w++){ units[w+h*map->width]->potential = extract(array[make_tuple(w,h)]); } } } which is fairly simple and actually works. Now, if I look further, I see there is a method called getshape() in array class, which gives back an object - I guess this object is a tuple, because the documentation is quite poor. So my idea is to get this object and use extract in order to get the actual dimensions as integers. but when I add this : void Layer::set_potentials (numeric::array& array) { object shape = array.getshape(); [...] } It compiles, and then on execution I get this error : AttributeError: 'numpy.ndarray' object has no attribute 'getshape' Does it still have nothing to do with Boost.Python ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Prob : IDLE can't import Tkinter
On May 10, 6:31 pm, Romain FEUILLETTE <[EMAIL PROTECTED]> wrote: > Hello, > > I'have just install Python 2.5.1 on Linux and the IDLE doesn't seem to > works because it didn't find Tcl/Tk > Perhaps you haven't installed Tkinter? I'm not sure which distribution you are using, but on my box (with Python2.4 installed) the relevant package is tkinter-2.4.4-1.fc6.rpm. -- http://mail.python.org/mailman/listinfo/python-list
How to convert Unicode string to raw string escaped with HTML Entities
Hi, I'm looking for a way to convert en unicode string encoded in UTF-8 to a raw string escaped with HTML Entities. I can't seem to find an easy way to do it. Quote from urllib will only work on ascii (which kind of defeat the purpose imho) and escape from cgi doesn't seems to do anything with my string. Any suggestion ? -- http://mail.python.org/mailman/listinfo/python-list
Re: replacing string in xml file--revisited
On May 10, 12:56 am, [EMAIL PROTECTED] wrote: > Hi, > I need to replace a string in xml file with something else.Ex > > - > rate > rate > > > > - > > Here i have opened an xml > file(small part is pasted here).I want to replace the word 'localId' > with 'dataPackageID' wherever it comes in xml file.I have asked this > before and got a code: > input_file = open(filename) > xmlcontents = input_file.read() > input_file.close() > xmlcontents = xmlcontents.replace("spam", "eggs") > output_file = open(filename,"w") > output_file.write(xmlcontents) > output_file.close() > > Although this works alone it is nto > working when i handle multiple file I/O.Is there a alternative to do > this.(maybe without read() operation) > Thanks After reading your post again, this might be better: #!/usr/bin/env python from elementtree import ElementTree as et tree = et.parse("testxml.xml") for t in tree.getiterator("SERVICEPARAMETER"): if t.get("Semantics") == "localId": t.set("Semantics", "dataPackageID") tree.write("output.xml") ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: preferred windows text editor?
T. Crane a écrit : > Right now I'm using Notepad++. What are other people using? > > trevis Notepad++ :-) And still use ConTEXT from time to time when I have big (MB) xml files to look at. -- http://mail.python.org/mailman/listinfo/python-list
Re: replacing string in xml file--revisited
On May 10, 1:42 pm, [EMAIL PROTECTED] wrote: > On May 10, 12:56 am, [EMAIL PROTECTED] wrote: > > > > > > > Hi, > > I need to replace a string in xml file with something else.Ex > > > - > > rate > > rate > > > > > > > > - > > > Here i have opened an xml > > file(small part is pasted here).I want to replace the word 'localId' > > with 'dataPackageID' wherever it comes in xml file.I have asked this > > before and got a code: > > input_file = open(filename) > > xmlcontents = input_file.read() > > input_file.close() > > xmlcontents = xmlcontents.replace("spam", "eggs") > > output_file = open(filename,"w") > > output_file.write(xmlcontents) > > output_file.close() > > > Although this works alone it is nto > > working when i handle multiple file I/O.Is there a alternative to do > > this.(maybe without read() operation) > > Thanks > > try this... > > #!/usr/bin/env python > > from elementtree import ElementTree as et > tree = et.parse("testxml.xml") > > for t in tree.getiterator("SERVICEPARAMETER"): > t.set("Semantics", "localId") > > tree.write("output.xml") > > ~Sean- Hide quoted text - > > - Show quoted text - #!/usr/bin/env python from elementtree import ElementTree as et tree = et.parse("testxml.xml") for t in tree.getiterator("SERVICEPARAMETER"): t.set("Semantics", "localId") tree.write("output.xml") Is this code complete,where are you replacing the localid with "datapackageid",and where is the new xml being stored. Thanks for the replies -- http://mail.python.org/mailman/listinfo/python-list
Re: Minor bug in tempfile module (possibly __doc__ error)
James T. Dennis <[EMAIL PROTECTED]> scribis: > In fact I realized, after reading through tempfile.py in /usr/lib/... > that the following also doesn't "work" like I'd expect: > ># foo.py >tst = "foo" >def getTst(arg): If I change this line: >return "foo-%s" % arg to: return "%s-%s" % (tst, arg) ># bar.py >import foo >foo.tst = "bar" >print foo.getTst("testing") > >foo-testing <<<- NOT "bar-testing" Then "python bar.py" prints "bar-testing". 0:[EMAIL PROTECTED]:/tmp> cat foo.py tst = "foo" def getTst(arg): return "%s-%s" % (tst,arg) 0:[EMAIL PROTECTED]:/tmp> cat bar.py import foo foo.tst = "bar" print foo.getTst("testing") 0:[EMAIL PROTECTED]:/tmp> python bar.py bar-testing And regarding the tempfile.template problem, this looks like a bug. Because all functions in tempfile taking a prefix argument use "def function(... , prefix=template, ...)", only the value of template at import time matters. Adiaŭ, Marc -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert Unicode string to raw string escaped with HTML Entities
ldng wrote: > Hi, > > I'm looking for a way to convert en unicode string encoded in UTF-8 to > a raw string escaped with HTML Entities. I can't seem to find an easy > way to do it. > > Quote from urllib will only work on ascii (which kind of defeat the > purpose imho) and escape from cgi doesn't seems to do anything with my > string. Probably worth having a look at this: http://effbot.org/zone/unicode-convert.htm TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: preferred windows text editor?
Ant wrote: > > What method of executing code snippets in a Python shell do other Vim > users use? Other than just copy/paste? > Not vim, but good old vi so should work in vim 1. Mark the start of the fragment, for exampls ms (to mark with label s). Labels a through z are available. 2. Move to the end of the fragment. 3. :'s,.w !python to send the fragment to the python interpreter Worked for me when I tried it a few minutes ago. I had never bothered before - just copied/pasted. Obviously, you can also mark the end, move to the start and do something like :.,'ew !python or mark both the start and the end, or use line numbers, or labels plus offsets, or searches, eg :/def/;+5w !python to search forward to the next occurrence of "def" and send that line plus the next five to the interpreter. Whatever works for you. The abbreviate and map commands can be used to reduce the typing if you are fanatical. Charles -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie (but improving) - Passing a function name with parameters as a parameter
Try again ... Just looking over your code quickly ... the function 'lookup' returns either True or False (a boolean) depending on whether matchcount == pattcount. Then in the declaration of the function 'timeloop' this return value gets bound to 'dofunction.' The subsequent call 'dofunction()' fails, because a boolean is not callable. Asun -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert Unicode string to raw string escaped with HTML Entities
On 10 mai, 11:03, Tim Golden <[EMAIL PROTECTED]> wrote: > > Probably worth having a look at this: > >http://effbot.org/zone/unicode-convert.htm Great ! You made my day :-) Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Simulating simple electric circuits
In article <[EMAIL PROTECTED]>, Bjoern Schliessmann <[EMAIL PROTECTED]> wrote: > Sounds more familiar than the analog approach. Maybe I misunderstood > something ... but I can't transfer my problem to this way of > thinking yet. My biggest problem is the fact that relays aren't > really interested in voltage, but current. > > Also, I find it difficult to transfer this circuit logic to boolean > logic I can contruct logic gates from. Sometimes, electric circuits > are used in different directions. Yep, the traditional digital simulation techniques don't apply very well to things like switches and relays. Going with a different approach is probably cleaner. > > I set up the mentioned "controller" which, at the beginning, tries > out all possible ways through the network and saves them. So, for > every possible circuit it knows which switches must be closed and > which relays will work if it's "on". In theory, it should now be > possible to try out every path, tell the relays if they have > voltage/current, and let the relays report back in to the > controller if their status changes so it can again test the > circuits that may have changed. I haven't tried out the last step, > but I will in the next days. Is there any logic error in my > strategy? Sounds reasonable. Depending on the size of your network, I might not worry too much about precomputing and saving information. If your circuit has loops in it (where the output of a later relay circles back to an earlier relay's coil), then it is possible for the circuit to oscillate, so you might have to be careful about this. For example, if your basic simulation flow was: 1) set initial conditions (switches, etc) 2) let power flow through the system 3) determine which relays will be thrown 4) if any relays have changed state, go to 2 Then an oscillating circuit would never quit. You might want to put a limit on the number of iterations through the loop, or logic that explicitly checks for oscillation. Or you could analyze the circuit ahead of time to see whether it has oscillation or not. Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert Unicode string to raw string escaped with HTML Entities
ldng wrote: > On 10 mai, 11:03, Tim Golden <[EMAIL PROTECTED]> wrote: >> Probably worth having a look at this: >> >>http://effbot.org/zone/unicode-convert.htm > > Great ! You made my day :-) > > Thanks. That's all right, but it's the effbot you need to thank. (Hope Fredrik's reading this). TJG -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple regex match idiom
On 9 Mai, 11:00, Hrvoje Niksic <[EMAIL PROTECTED]> wrote: > I often have the need to match multiple regexes against a single > string, typically a line of input, like this: > > if (matchobj = re1.match(line)): > ... re1 matched; do something with matchobj ... > elif (matchobj = re2.match(line)): > ... re2 matched; do something with matchobj ... > elif (matchobj = re3.match(line)): > > > Of course, that doesn't work as written because Python's assignments > are statements rather than expressions. The obvious rewrite results > in deeply nested if's: > > matchobj = re1.match(line) > if matchobj: > ... re1 matched; do something with matchobj ... > else: > matchobj = re2.match(line) > if matchobj: > ... re2 matched; do something with matchobj ... > else: > matchobj = re3.match(line) > if matchobj: > ... > > Normally I have nothing against nested ifs, but in this case the deep > nesting unnecessarily complicates the code without providing > additional value -- the logic is still exactly equivalent to the > if/elif/elif/... shown above. > > There are ways to work around the problem, for example by writing a > utility predicate that passes the match object as a side effect, but > that feels somewhat non-standard. I'd like to know if there is a > Python idiom that I'm missing. What would be the Pythonic way to > write the above code? Instead of scanning the same input over and over again with different, maybe complex, regexes and ugly looking, nested ifs, i would suggest defining a grammar and do parsing the input once with registered hooks for your matching expressions. SimpleParse (http://simpleparse.sourceforge.net) with a DispatchProcessor or pyparsing (http://pyparsing.wikispaces.com/) in combination with setParseAction or something similar are your friends for such a task. Steffen -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie (but improving) - Passing a function name with parameters as a parameter
On 10 Mai, 10:27, mosscliffe <[EMAIL PROTECTED]> wrote: > I am trying to time a function's execution, Do you know the timeit module ? : Tool for measuring execution time of small code snippets Steffen -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie (but improving) - Passing a function name with parameters as a parameter
As Stephan said, you can investigate the timeit module. If you want to test it your way, wrap up your function call in another function: On May 10, 9:27 am, mosscliffe <[EMAIL PROTECTED]> wrote: ... > def timeloop(dofunction,iters=10): ... > > def lookup(recs,patterns): ... > myrecs = ... > def test1(): lookup(myrecs, ['one', 'nomatch']) def test2(): lookup(myrecs, ['one', 'two']) > timeloop(test1, 10) Using timeit: t = timeit.Timer("lookup(myrecs, ['one', 'nomatch'])", "from __main__ import *") print t.timeit(10) -- Ant. -- http://mail.python.org/mailman/listinfo/python-list
Re: msbin to ieee
On May 6, 6:44 pm, revuesbio <[EMAIL PROTECTED]> wrote: > Hi > Does anyone have the python version of the conversion from msbin to > ieee? > Thank u Not sure if this helps, but I think this thread has the answer; http://groups.google.com/group/comp.lang.python/browse_thread/thread/286d9f6daff9bfab/ce76d5fcd887a47d?lnk=gst&q=geskerrett&rnum=2#ce76d5fcd887a47d Check out the response from Bengt Richter. His function did the right thing. -- http://mail.python.org/mailman/listinfo/python-list
Re: matplotlib problem
On 10 Mai, 10:31, redcic <[EMAIL PROTECTED]> wrote: > I've got a question regarding matplotlib. I use the command: > pylab.plot(...) > to create a graph. > Then, the execution of the code stops after the line: > pylab.show() > which is off course the last line of my code. > > My problem is that I have to close the figure window before in order > to finish the execution of my code. > I'd like to be able to launch my program other times with different > parameters without having to close the figure windows before each > launch. > Just so you know, I'm using TkAgg backend and the SciTE editor. > > Following the answer I was given in the > thread:http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > I set "interactive : True" in matplotlibrc. > I also tried the other things I had been advised to do but I still > have the same problem. > > Any other idea ? > > Thanks, > > Cédric Use ipython (http://ipython.scipy.org/moin/) : IPython accepts the special option -pylab (Sec. 5.2). This configures it to support matplotlib, honoring the settings in the .matplotlibrc file. IPython will detect the user's choice of matplotlib GUI backend, and automatically select the proper threading model to prevent blocking. It also sets matplotlib in interactive mode and modifies %run slightly, so that any matplotlib-based script can be executed using %run and the final show() command does not block the interactive shell. Steffen -- http://mail.python.org/mailman/listinfo/python-list
Re: replacing string in xml file--revisited
On May 10, 1:55 pm, [EMAIL PROTECTED] wrote: > On May 10, 12:56 am, [EMAIL PROTECTED] wrote: > > > > > > > Hi, > > I need to replace a string in xml file with something else.Ex > > > - > > rate > > rate > > > > > > > > - > > > Here i have opened an xml > > file(small part is pasted here).I want to replace the word 'localId' > > with 'dataPackageID' wherever it comes in xml file.I have asked this > > before and got a code: > > input_file = open(filename) > > xmlcontents = input_file.read() > > input_file.close() > > xmlcontents = xmlcontents.replace("spam", "eggs") > > output_file = open(filename,"w") > > output_file.write(xmlcontents) > > output_file.close() > > > Although this works alone it is nto > > working when i handle multiple file I/O.Is there a alternative to do > > this.(maybe without read() operation) > > Thanks > > After reading your post again, this might be better: > > #!/usr/bin/env python > > from elementtree import ElementTree as et > tree = et.parse("testxml.xml") > > for t in tree.getiterator("SERVICEPARAMETER"): > if t.get("Semantics") == "localId": > t.set("Semantics", "dataPackageID") > > tree.write("output.xml") > > ~Sean- Hide quoted text - > > - Show quoted text - which module should be imported for above to work,it says ImportError: No module named elementtree Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie (but improving) - Passing a function name with parameters as a parameter
Many thanks. I think I see what you mean. I will try 'timeit' as well. Aren't examples wonderful ? On 10 May, 11:42, Ant <[EMAIL PROTECTED]> wrote: > As Stephan said, you can investigate the timeit module. If you want to > test it your way, wrap up your function call in another function: > > On May 10, 9:27 am, mosscliffe <[EMAIL PROTECTED]> wrote: > ...> def timeloop(dofunction,iters=10): > ... > > > def lookup(recs,patterns): > > ... > > > myrecs = ... > > def test1(): > lookup(myrecs, ['one', 'nomatch']) > > def test2(): > lookup(myrecs, ['one', 'two']) > > > timeloop(test1, 10) > > Using timeit: > > t = timeit.Timer("lookup(myrecs, ['one', 'nomatch'])", "from __main__ > import *") > print t.timeit(10) > > -- > Ant. -- http://mail.python.org/mailman/listinfo/python-list
Re: PYDOC replacement. (Was:Sorting attributes by catagory)
Nick Vatamaniuc wrote: > Thanks for the info, Ron. I had no idea pydoc was that powerful! > -Nick Change *was* to *will be*. It really needed to be re factored. ;-) Cheers, Ron -- http://mail.python.org/mailman/listinfo/python-list
Re: preferred windows text editor?
At 11:06 AM 5/9/2007, T. Crane wrote: >Right now I'm using Notepad++. What are other people using? Ulipad. Dick Moores -- http://mail.python.org/mailman/listinfo/python-list
Re: Change serial timeout per read
> you will probably have to make the port non blocking, and roll your own > using different time.sleep(n) values between invocations to port.read(1) calls What I actually want to do is to respond immediately if the expected string comes in, but not raise a timeout unless it takes longer than the maximum time. So if the device I'm communicating with usually responds in a second, but _can_ take up to 20 seconds, I don't want to do a sleep(20) then read the port since this will slow everything down a lot in an average world. I want to keep checking for the expected string, and act upon it as soon as I've got it, only raising a timeout if I haven't got it after 20 seconds. I guess to do this using non- blocking calls I have to do something like: timesofar = 0 returnstring = port.read(1) while len(returnstring)= timeout: raise SerialException('Timeout') time.sleep(checkportinterval) timesofar += checkpointinterval returnstring += port.read(1) This seems rather messy. What I've tried this morning is to produce a modified version of uspp with a second optional timeout parameter in its read() function. If this is present, the timeout given is sent to the port using SetCommTimeouts(). If it's not present, the timeouts specified when the port was opened are sent. At first sight, with minimal testing on Windows, this seems to be working, and will leave my application code a lot cleaner than the non-blocking plus sleep approach. Of course I don't know whether my method will work on Linux, and there may be problems I haven't found yet. Rowan -- http://mail.python.org/mailman/listinfo/python-list
Re: msbin to ieee
On May 10, 8:48 pm, imageguy <[EMAIL PROTECTED]> wrote: > On May 6, 6:44 pm, revuesbio <[EMAIL PROTECTED]> wrote: > > > Hi > > Does anyone have the python version of the conversion from msbin to > > ieee? > > Thank u > > Not sure if this helps, but I think this thread has the > answer;http://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > Check out the response from Bengt Richter. His function did the right > thing. Yes, Bengt's function did the right thing on the input for that particular problem, which involved IEEE 64-bit floating point numbers stored in little-endian format. The current problem involves 32-bit MBF (Microsoft Binary/Basic Floating-point/Format) numbers. Different problem. -- http://mail.python.org/mailman/listinfo/python-list
Re: Single precision floating point calcs?
Grant Edwards <[EMAIL PROTECTED]> wrote: >In the C implementations, the algorithms will be done >implemented in single precision, so doing my Python prototyping >in as close to single precision as possible would be "a good >thing". Something like numpy might give you reproducable IEEE 32-bit floating point arithmetic, but you may find it difficult to get that out of a IA-32 C compiler. IA-32 compilers either set the x87 FPU's precision to either 64-bits or 80-bits and only round results down to 32-bits when storing values in memory. If you can target CPUs that support SSE, then compiler can use SSE math to do most single precision operations in single precision, although the compiler may not set the required SSE flags for full IEEE complaince. In other words, since you're probably going to have to allow for some small differences in results anyways, it may not be worth the trouble of trying to get Python to use 32-bit floats. (You might also want to consider whether you want to using single precision in your C code to begin with, on IA-32 CPUs it seldom makes a difference in performance.) Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] [EMAIL PROTECTED] -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // -- http://mail.python.org/mailman/listinfo/python-list
Thread-safe dictionary
Hi, please consider the following code: from __future__ import with_statement class safe_dict(dict): def __init__(self, *args, **kw): self.lock = threading.Lock() dict.__init__(self, *args, **kw) def __getitem__(self, key): with self.lock: return dict.__getitem__(self, key) def __setitem__(self, key, value): with self.lock: dict.__setitem__(self, key, value) def __delitem__(self, key): with self.lock: dict.__delitem__(self, key) - would I need to override another methods e.g. update() or items() in order to remain thread-safe or is this enough? - in __getitem__, does it release the lock after returning the item? - wouldn't it be better to use threading.RLock, mutex, ... instead? Thanks a lot! -- http://mail.python.org/mailman/listinfo/python-list
Re: Designing a graph study program
On 9 Mag, 09:10, Alexander Schliep <[EMAIL PROTECTED]> wrote: > andrea <[EMAIL PROTECTED]> writes: > > Well then I wanted to draw graphs and I found that pydot is working > > really nicely. > > BUT I'd like to do this, an interactive program to see ho the > > algorithms works... > > For example in the breath search first, every time the algorithm > > colors a node, the program should redraw the graphs. Which modules > > should I use for graphics (I use macosX and I'd like something cross > > platforms). > > Check outhttp://gato.sf.net(LGPL license). It does exactly what you > want to do and there is a binary for MacOS X. Algorithms are implemented > using Gato's graph class and rudimentary visualizations you get for free > by replacing standard data structures (e.g., a vertex queue) by > animated ones (AnimatedVertexQueue). > > There is a Springer textbook forthcoming. We are also starting to collect > contributed algorithms, which we would like to make available from > our website. > > Full disclosure: I am the author of Gato > > Best, > Alexander Very very nice well done! I'd like to do something similar, just to learn something new... Could you explain me how you designed it?? How is the step mechanism done?? Any advices? -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread-safe dictionary
On 10 May 2007 05:45:24 -0700, [EMAIL PROTECTED] wrote: >Hi, > >please consider the following code: > > >from __future__ import with_statement > >class safe_dict(dict): >def __init__(self, *args, **kw): >self.lock = threading.Lock() >dict.__init__(self, *args, **kw) >def __getitem__(self, key): >with self.lock: >return dict.__getitem__(self, key) >def __setitem__(self, key, value): >with self.lock: >dict.__setitem__(self, key, value) >def __delitem__(self, key): >with self.lock: >dict.__delitem__(self, key) > > >- would I need to override another methods e.g. update() or items() in >order to remain thread-safe or is this enough? >- in __getitem__, does it release the lock after returning the item? >- wouldn't it be better to use threading.RLock, mutex, ... instead? > The builtin dict type is already thread safe. Jean-Paul -- http://mail.python.org/mailman/listinfo/python-list
trouble with generators
Hi Pythonistas, I'm stuck in a maze of new style classes and generators. While I love the concepts, I obviously didn't grok them throughout. I'm trying to generate a bunch of similar classes, where some are contained in list attributes of others, e.g.: class A: def __init__(self): self.id = 'A1' self.b = [instances of B] class B: def __init__(self): self.id = 'B1' Here's the test code, I have: #!/usr/bin/env python # -*- coding: utf8 -*- class A(object): "A" def __init__(self): self.id = None self.b = [] class B(object): "B" def __init__(self): self.id = None class Gen(object): def records(self, cls): for i in range(3): setattr(cls, "id", "%s%s" % (cls.__doc__, i)) yield cls def display(self, rec): for i in rec.__dict__.keys(): if not i.startswith("_"): print "%s: %s: %s" % (rec.__doc__, i, rec.__dict__[i]) class GenA(Gen): def __init__(self): self.genB = GenB() def records(self): for a in Gen.records(self, A()): for b in self.genB.records(): #self.genB.display(b) a.b.append(b) #self.display(a) yield a class GenB(Gen): def records(self): return Gen.records(self, B()) # testing.. aRecs = [] bRecs = [] for i, r in enumerate(GenB().records()): bRecs.append(r) print i, r.id, r for i, r in enumerate(GenA().records()): aRecs.append(r) print i, r.id, r for b in r.b: print b.id, b Here's the commented output: # even if I keep a reference to each rec, the object is reused: 0 B0 <__main__.B object at 0xb7bd0f8c> 1 B1 <__main__.B object at 0xb7bd0f8c> 2 B2 <__main__.B object at 0xb7bd0f8c> # same here, with additional quadratic behavior, I do not understand 0 A0 <__main__.A object at 0xb7bd206c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd210c> 1 A1 <__main__.A object at 0xb7bd206c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd20ec> B2 <__main__.B object at 0xb7bd20ec> B2 <__main__.B object at 0xb7bd20ec> 2 A2 <__main__.A object at 0xb7bd206c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd210c> B2 <__main__.B object at 0xb7bd20ec> B2 <__main__.B object at 0xb7bd20ec> B2 <__main__.B object at 0xb7bd20ec> B2 <__main__.B object at 0xb7bd0f8c> B2 <__main__.B object at 0xb7bd0f8c> B2 <__main__.B object at 0xb7bd0f8c> I expected to get 3 different class objects from both sections, with each A containing 3 different Bs in the latter section, but obviously got something else. Could some kind soul help me to distangle my mind twist here? Am I healable? TIA, Pete -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread-safe dictionary
Jean-Paul Calderone schrieb: > On 10 May 2007 05:45:24 -0700, [EMAIL PROTECTED] wrote: >> Hi, >> >> please consider the following code: >> >> >> from __future__ import with_statement >> >> class safe_dict(dict): >>def __init__(self, *args, **kw): >>self.lock = threading.Lock() >>dict.__init__(self, *args, **kw) >>def __getitem__(self, key): >>with self.lock: >>return dict.__getitem__(self, key) >>def __setitem__(self, key, value): >>with self.lock: >>dict.__setitem__(self, key, value) >>def __delitem__(self, key): >>with self.lock: >>dict.__delitem__(self, key) >> >> >> - would I need to override another methods e.g. update() or items() in >> order to remain thread-safe or is this enough? >> - in __getitem__, does it release the lock after returning the item? >> - wouldn't it be better to use threading.RLock, mutex, ... instead? >> > > The builtin dict type is already thread safe. Technically - yes. But you should mention that the reason for that is the GIL, which essentially ensures that python as whole is threadsafe on the level of assignments, collection manipulation and so forth. At the cost of not being able to have real concurrent threads except for C-code that explicitly releases the GIL. Diez -- http://mail.python.org/mailman/listinfo/python-list
RE: change of random state when pyc created??
> From: Alan Isaac > > I'm sure my first pass will be flawed, but here goes: > > http://docs.python.org/lib/typesmapping.html: > to footnote (3), add phrase "which may depend on the memory location of > the > keys" to get: > > Keys and values are listed in an arbitrary order, > which may depend on the memory location of the keys. > This order is non-random, varies across Python implementations, > and depends on the dictionary's history of insertions and deletions. > > http://docs.python.org/lib/types-set.html: append a new sentence to 2nd > paragraph > > Iteration over a set returns elements in an arbitrary order, > which may depend on the memory location of the elements. It's possible there are other factors that can affect this as well. A more general statement is probably more appropriate: "Keys and values are listed in an arbitrary order. This order is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions as well as factors outside the scope of the containing program." "Iteration over a set returns elements in an arbitrary order, which may depend on factors outside the scope of the containing program." --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
RE: change of random state when pyc created??
On Thu, 2007-05-10 at 08:01 -0500, Hamilton, William wrote: > It's possible there are other factors that can affect this as well. A more > general statement is probably more appropriate: > > "Keys and values are listed in an arbitrary order. This order is > non-random, varies across Python implementations, and depends on the > dictionary's history of insertions and deletions as well as factors outside > the scope of the containing program." I think we should remove any implied reliability and slash it down to this: "Keys and values are listed in an arbitrary order that is random except that if items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond." > "Iteration over a set returns elements in an arbitrary order, which may > depend on factors outside the scope of the containing program." And this: "Iteration over a set returns elements in random order." Regards, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: change of random state when pyc created??
>> Alan Isaac requested: >> http://docs.python.org/lib/typesmapping.html: to footnote (3), add phrase >> http://docs.python.org/lib/types-set.html: append a new sentence to 2nd paragraph "Hamilton, William " <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > "Keys and values are listed in an arbitrary order. This order is > non-random, varies across Python implementations, and depends on the > dictionary's history of insertions and deletions as well as factors outside > the scope of the containing program." > "Iteration over a set returns elements in an arbitrary order, which may > depend on factors outside the scope of the containing program." I think this is good and might have clued me in. At least I'd have had a fighting chance this way. Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
keyword checker - keyword.kwlist
Hi I try to check whether a given input is keyword or not. However this script won't identify keyword input as a keyword. How should I modify it to make it work? #!usr/bin/env python import keyword input = raw_input('Enter identifier to check >> ') if input in keyword.kwlist: print input + "is keyword" else: print input + "is not keyword" -- http://mail.python.org/mailman/listinfo/python-list
Re: Towards faster Python implementations - theory
On May 8, 5:53 pm, John Nagle <[EMAIL PROTECTED]> wrote: > The point here is that we don't need language changes or declarations > to make Python much faster. All we need are a few restrictions that > insure that, when you're doing something unusual, the compiler can > tell. Franz, CMUCL, SBCL and GCL teams made Lisp almost as fast as C. A dynamic language can be fast if the implementation is good. If you look at SBCL and GCL, no code is interpreted. It's all compiled on the fly to native machine code. The compiler begins with some code and some input data, and compiles as much as it can. Then the RT executes the machine code, compiles again, etc. Often long stretches of code can be compiled without break, and tight performance critical loops are usually compiled only once. In addition to this, one needs an efficient system to cache compiled code, in order to do the compilation work only once. making a dynamic language fast is not rocket science. We should have somthing like "GPython", a Python RT on top of a GCC backend, similar to what the GCL team did for Lisp. There is no obvious reason as to why Lisp should have better performance than Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Single precision floating point calcs?
On May 9, 6:51 pm, Grant Edwards <[EMAIL PROTECTED]> wrote: > Is there any way to do single-precision floating point > calculations in Python? Yes, use numpy.float32 objects. > I know the various array modules generally support arrays of > single-precision floats. I suppose I could turn all my > variables into single-element arrays, but that would be way > ugly... Numpy has scalars as well. >>> import numpy >>> a = numpy.float32(2.0) >>> b = numpy.float32(8.0) >>> c = a+b >>> print c 10.0 >>> type(c) >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Suggestions for how to approach this problem?
James Stroud wrote: > I included code in my previous post that will parse the entire bib, > making use of the numbering and eliminating the most probable, but still > fairly rare, potential ambiguity. You might want to check out that code, > as my testing it showed that it worked with your example. Thanks. It looked a little involved so I hadn't started to work through it yet, but I'll do that now before I actually try to write something from scratch. :) -- http://mail.python.org/mailman/listinfo/python-list
Re: Single precision floating point calcs?
On 2007-05-10, Ross Ridge <[EMAIL PROTECTED]> wrote: > Grant Edwards <[EMAIL PROTECTED]> wrote: >>In the C implementations, the algorithms will be done >>implemented in single precision, so doing my Python prototyping >>in as close to single precision as possible would be "a good >>thing". > > Something like numpy might give you reproducable IEEE 32-bit > floating point arithmetic, but you may find it difficult to > get that out of a IA-32 C compiler. That's OK, I don't run the C code on an IA32. The C target is a Hitachi H8/300. > (You might also want to consider whether you want to using > single precision in your C code to begin with, on IA-32 CPUs > it seldom makes a difference in performance.) Since I'm running the C code on a processor without HW floating point support, using single precision makes a big difference. -- Grant Edwards grante Yow! I have many CHARTS at and DIAGRAMS.. visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Thread-safe dictionary
Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: >>- would I need to override another methods e.g. update() or items() in >>order to remain thread-safe or is this enough? No, you'll need to protect almost everything. items may be safe. update, clear, get, has_key, pop, and setdefault all need a lock in the general case. Also be aware that some Python internals bypass things like __getitem__ in dict subclasses, so the lock will be ignored if (for example) you use the dict as a namespace for exec. >>- in __getitem__, does it release the lock after returning the item? >>- wouldn't it be better to use threading.RLock, mutex, ... instead? >> > > The builtin dict type is already thread safe. It very much depends on what you mean by 'thread safe'. Calls to dict methods from multiple threads won't result in Python getting into an inconsistent state and crashing, but they aren't necessarily atomic either. In particular, any method which can modify the content of the dictionary could release an instance of a class with a __del__ method written in Python and other threads will be able to run at that point. Likewise any lookup in a dict where a key is an instance of a class with user-defined comparison method could allow Python code and therefore other threads to run. Of course if your particular dict objects all use simple types this may not matter, but it needs a careful programmer to use an ordinary Python dict (or list) safely across threads. IMHO you are probably best to write a thread-safe class which uses an ordinary dict (and has a nicely limited interface) rather than trying to produce a completely thread-safe dict type. -- http://mail.python.org/mailman/listinfo/python-list
How to installo????
Just got a new Vista system and puter Installed a newer version of Python, up from 2.2 or so... Tried to install Win extensions, but have forgotten how it's done. Clicking on setup in the Win Extsions package flashes a window by, but cannot read it. and I don't see a way to load the setup into Python without Win Extensions. Any suggestions? Thank you -- http://mail.python.org/mailman/listinfo/python-list
Re: Towards faster Python implementations - theory
sturlamolden wrote: > On May 8, 5:53 pm, John Nagle <[EMAIL PROTECTED]> wrote: > >> The point here is that we don't need language changes or declarations >> to make Python much faster. All we need are a few restrictions that >> insure that, when you're doing something unusual, the compiler can >> tell. > > Franz, CMUCL, SBCL and GCL teams made Lisp almost as fast as C. A > dynamic language can be fast if the implementation is good. > > If you look at SBCL and GCL, no code is interpreted. It's all compiled > on the fly to native machine code. The compiler begins with some code > and some input data, and compiles as much as it can. Then the RT > executes the machine code, compiles again, etc. Often long stretches > of code can be compiled without break, and tight performance critical > loops are usually compiled only once. In addition to this, one needs > an efficient system to cache compiled code, in order to do the > compilation work only once. making a dynamic language fast is not > rocket science. > > We should have somthing like "GPython", a Python RT on top of a GCC > backend, similar to what the GCL team did for Lisp. There is no > obvious reason as to why Lisp should have better performance than > Python. I doubt if anyone disputes the gist of what you're saying[*], viz that Python could be made faster by using technique (a), (b) or (c) which have been successful elsewhere. At least that it's worth investgating. But the relevant bit of your last paragraph is at the start: "We should...". Unless someone or someones has the time, inclination, money, backing, wherewithal etc. to implement this or any other measure of speeding-up, it's all pie-in-the-sky. Useful, maybe, as discussion of what options are viable, but a project of this magnitude doesn't just happen in some developer's lunchbreak. Many people (and I include myself) are quite happy with Python's speed. In fact, I'm quite happy with most things about Python. Others would like to see it faster. That's great. But unless people puts their money where their mouths are, I don't see it happening. TJG [*] Actually, knowing this community, I'm sure *someone's* going to! -- http://mail.python.org/mailman/listinfo/python-list
newb: Python Module and Class Scope
Can a class inside a module, access a method, outside of class, but inside of the module? Eg. Can instance of class a access main, if so how? What is the scope of "def main()" interms of class A? myModule: class A: main() def main(): thnx. -- http://mail.python.org/mailman/listinfo/python-list
Re: newb: Python Module and Class Scope
This works for me.Also tried importing this module into another program. The class is inside the module so like the different function's of a module can access each other,the same thing applies to a class and functions/classes #Test Module class foo: def __init__(self): self.data=1 def outData(self): print self.data main() def main(): print "I am the main" #Module test if __name__=="__main__": fooObj=foo() fooObj.outData() On 10 May 2007 07:02:49 -0700, johnny <[EMAIL PROTECTED]> wrote: Can a class inside a module, access a method, outside of class, but inside of the module? Eg. Can instance of class a access main, if so how? What is the scope of "def main()" interms of class A? myModule: class A: main() def main(): thnx. -- http://mail.python.org/mailman/listinfo/python-list -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -- http://mail.python.org/mailman/listinfo/python-list
Re: keyword checker - keyword.kwlist
On 10 Mag, 15:38, [EMAIL PROTECTED] wrote: > Hi > > I try to check whether a given input is keyword or not. However this > script won't identify keyword input as a keyword. How should I modify it > to make it work? > > #!usr/bin/env python > import keyword > > input = raw_input('Enter identifier to check >> ') > if input in keyword.kwlist: > print input + "is keyword" > > else: > print input + "is not keyword" Hmm... I tried, and identify it. Try to change the 'input' variable name with other... -- http://mail.python.org/mailman/listinfo/python-list
Re: newb: Python Module and Class Scope
johnny <[EMAIL PROTECTED]> wrote: > Can a class inside a module, access a method, outside of class, but > inside of the module? > > Eg. Can instance of class a access main, if so how? What is the > scope of "def main()" interms of class A? > > myModule: > > class A: >main() > > def main(): > > > thnx. > > Yes;by using its name;global scope. Why not try it for yourself? N.B. Functions in Python do not exist until the def statement is executed, so the code like your sample will fail to find 'main' if you try to call it from inside the class body. A call from inside an instance method would be fine though (provided you didn't call it until main was defined), or a call from the class body would also be fine provided you define main before you define the class. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make Python poll a PYTHON METHOD
Is it possible to call threads inside another thread (nested threads)? The example above creates a thread to call a function "eat" every time based on a specified interval. Now for example, if I make the called function "eat" to spawn threads to do the work in a queue and when all jobs are done, spawned threads join. When the next interval is up this process repeat itself. Thanks. On May 7, 11:19 pm, Nick Vatamaniuc <[EMAIL PROTECTED]> wrote: > On May 7, 10:42 pm, Nick Vatamaniuc <[EMAIL PROTECTED]> wrote: > > > > > On May 7, 10:07 pm, johnny <[EMAIL PROTECTED]> wrote: > > > > Is there a way to call a function on a specified interval(seconds, > > > milliseconds) every time, like polling user defined method? > > > > Thanks. > > > Sure, > > > >>> def baz(): > > >...: print "Baz!" > >...: > > > >>> from threading import Timer > > >>> timer=Timer(5.0,baz) > > >>> timer.start() > > >>> Baz! > > > Cheers, > > -Nick Vatamaniuc > > By the way, here is another way to do it. This way it will repeat, the > other one executed once. Of course, if it executed once, you can make > it do it again, but there is some trickery involved. Here is a way to > do it using threads. > > Hope it helps, > -Nick Vatamaniuc > > from threading import Thread > from time import sleep > > class Repeater(Thread): > def __init__(self,interval,fun,*args,**kw): > Thread.__init__(self) > self.interval=interval > self.fun=fun > self.args=args > self.kw=kw > self.keep_going=True > > def run(self): >while(self.keep_going): > sleep(self.interval) > self.fun(*self.args,**self.kw) > > def stop_repeating(self): > self.keep_going=False > > def eat(*a): > print "eating: " , ','.join([stuff for stuff in a]) > > r=Repeater(1.0, eat, 'eggs','spam','kelp') > r.start() > sleep(6.0) > r.stop_repeating() -- http://mail.python.org/mailman/listinfo/python-list
Read binary data from MySQL database
Hello, I try to write a python application with wx that shows images from a MySQL database. I use the following code to connect and get data when some event was triggered: dbconn = MySQLdb.connect(host="localhost", user="...", passwd="...", db="images") dbcurs = dbconn.cursor() dbcurs.execute("""SELECT imgdata FROM images LIMIT 1""") imgstring = dbcurs.fetchone()[0] frame.showImage(imgstring) Within my frame, the following method is defined: def showImage(self, imgstring): imgdata = StringIO.StringIO() imgdata.write(imgstring) print imgdata.getvalue() wx.ImageFromStream(imgdata, wx.BITMAP_TYPE_GIF) panel = wx.Panel(self, -1) self.panel = panel But this does not work. The converter says that the data is not valid GIF. When I print the content of imgstring after the database select statement, it contains something like this: array('c', 'GIF89aL\x01=\x01\x85\x00\x00\x00\x00\x00\xff\xff\xff \x00\xff\xff\xff[...]\x00\x00;') When I try to print imgstring[1], the result is "I". So I don't quite get what this print result is about and why my input should not be valid. The data in the database is correct, I can restore the image with tools like the MySQL Query Browser. Thanks in advance, Christoph -- http://mail.python.org/mailman/listinfo/python-list
Re: Read binary data from MySQL database
On Thu, 2007-05-10 at 07:19 -0700, Christoph Krammer wrote: > Hello, > > I try to write a python application with wx that shows images from a > MySQL database. I use the following code to connect and get data when > some event was triggered: > > dbconn = MySQLdb.connect(host="localhost", user="...", passwd="...", > db="images") > dbcurs = dbconn.cursor() > dbcurs.execute("""SELECT imgdata FROM images LIMIT 1""") > imgstring = dbcurs.fetchone()[0] > frame.showImage(imgstring) > > Within my frame, the following method is defined: > > def showImage(self, imgstring): > imgdata = StringIO.StringIO() > imgdata.write(imgstring) > print imgdata.getvalue() > wx.ImageFromStream(imgdata, wx.BITMAP_TYPE_GIF) > panel = wx.Panel(self, -1) > self.panel = panel > > But this does not work. The converter says that the data is not valid > GIF. When I print the content of imgstring after the database select > statement, it contains something like this: > > array('c', 'GIF89aL\x01=\x01\x85\x00\x00\x00\x00\x00\xff\xff\xff > \x00\xff\xff\xff[...]\x00\x00;') That means that imgstring is not a string, it's an array of characters. Observe: >>> import array >>> a = array.array('c', 'Blahblahblah') >>> print a array('c', 'Blahblahblah') >>> str(a) "array('c', 'Blahblahblah')" >>> a.tostring() 'Blahblahblah' Calling write() with an object that's not a string will implicitly call str() on that object and write the result of that call to the file. Try imgdata.write(imgstring.tostring()) to extract the string data from the array. Hope this helps, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Read binary data from MySQL database
On Do, 10.05.2007, 16:19, Christoph Krammer wrote: > Hello, > > I try to write a python application with wx that shows images from a > MySQL database. I use the following code to connect and get data when > some event was triggered: > > dbconn = MySQLdb.connect(host="localhost", user="...", passwd="...", > db="images") > dbcurs = dbconn.cursor() > dbcurs.execute("""SELECT imgdata FROM images LIMIT 1""") > imgstring = dbcurs.fetchone()[0] > frame.showImage(imgstring) > > Within my frame, the following method is defined: > > def showImage(self, imgstring): > imgdata = StringIO.StringIO() > imgdata.write(imgstring) Use imgdata.write(imgstring.tostring()) or imgstring.tofile(imgdata) > print imgdata.getvalue() > wx.ImageFromStream(imgdata, wx.BITMAP_TYPE_GIF) > panel = wx.Panel(self, -1) > self.panel = panel > > But this does not work. The converter says that the data is not valid > GIF. When I print the content of imgstring after the database select > statement, it contains something like this: > > array('c', 'GIF89aL\x01=\x01\x85\x00\x00\x00\x00\x00\xff\xff\xff > \x00\xff\xff\xff[...]\x00\x00;') > > When I try to print imgstring[1], the result is "I". So I don't quite > get what this print result is about and why my input should not be > valid. The data in the database is correct, I can restore the image > with tools like the MySQL Query Browser. > > Thanks in advance, > Christoph > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- http://mail.python.org/mailman/listinfo/python-list
Re: High resolution sleep (Linux)
On 9 Maj, 03:23, John Nagle <[EMAIL PROTECTED]> wrote: > Hendrik van Rooyen wrote: > > "Tim Roberts" <[EMAIL PROTECTED]> wrote" > > It is also possible to keep the timer list sorted by "expiry date", > > and to reprogram the timer to interrupt at the next expiry time > > to give arbitrary resolution, instead of implementing a regular 'tick'. > > Yes, and that's a common feature in real-time operating systems. > If you're running QNX, you can expect that if your high priority > task delays to a given time, you WILL get control back within a > millisecond of the scheduled time. Even tighter timing control > is available on some non-x86 processors. > > Some CPUs even have hardware support for a sorted event list. > The Intel 8061, which ran the engines of most Ford cars in the 1980s, > had that. > > But no way are you going to get consistent timing resolution like that > from Python. It's an interpreter with a garbage collector, after all. > > John Nagle The application the original poster (i.e. me) was interested in was a program that sends ethernet packets at a loosely specified rate. A loop that sends all packets with no sleep in between will send them at a too high rate. Using the default sleep in my Python interpreter sleeps to long, since even a few microseconds add up when you send hundreds of thousands of packets. If the process scheduler deals with another process now and then, it doesn't matter. If it switches to another application between each packet is beeing sent, that's a problem. Anyways, what I need is high resolution sleep, not high resolution timing. Installing a real time OS seems like overkill. (Yes I know, one can also send, say, 50 packets at a time, and then sleep, send 50 more packets, and so on.) -- http://mail.python.org/mailman/listinfo/python-list
Re: preferred windows text editor?
On Wed, 9 May 2007 13:06:52 -0500, "T. Crane" <[EMAIL PROTECTED]> wrote: >Right now I'm using Notepad++. What are other people using? SPE, out of the trunk. http://sourceforge.net/projects/spe/ John -- http://mail.python.org/mailman/listinfo/python-list
ANN: parley 0.2
Release Announcement: PARLEY version 0.2 PARLEY is an API for writing Python programs that implement the Actor model of distributed systems, in which lightweight concurrent processes communicate through asynchronous message-passing. Actor systems typically are easier to write and debug than traditional concurrent programs that use locks and shared memory. PARLEY can run using either traditional native threads or user-space threads (i.e. the "tasklets" implemented by Stackless Python). A program written using PARLEY can choose between the two by changing a single line of code. Code samples, documentation, and source code can be found at the PARLEY home page: http://osl.cs.uiuc.edu/parley/ PARLEY is licensed under the LGPL. -- Jacob Lee <[EMAIL PROTECTED]> -- http://mail.python.org/mailman/listinfo/python-list
Re: keyword checker - keyword.kwlist
> > Hmm... I tried, and identify it. > Try to change the 'input' variable name with other... > Changed input variable to myInput, but the result is still the same. for example, 'else' isn't identified as a keyword by the script though it exists in keyword.kwlist. -- http://mail.python.org/mailman/listinfo/python-list
Re: How to make Python poll a PYTHON METHOD
On 2007-05-10, johnny <[EMAIL PROTECTED]> wrote: > Is it possible to call threads inside another thread (nested threads)? No. It's not possible to call threads because they're not callable objects. (I'm assuming you're talking about Thread objects from the threading module.) If you're asking if you can create and start threads from a non-main thread, the answer is yes. > The example above creates a thread to call a function "eat" > every time based on a specified interval. Now for example, if > I make the called function "eat" to spawn threads to do the > work in a queue and when all jobs are done, spawned threads > join. When the next interval is up this process repeat > itself. OK. -- Grant Edwards grante Yow! I demand IMPUNITY! at visi.com -- http://mail.python.org/mailman/listinfo/python-list
SQLObject 0.7.7
Hello! I'm pleased to announce the 0.7.7 release of SQLObject. What is SQLObject = SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject == Site: http://sqlobject.org Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.7.7 News and changes: http://sqlobject.org/docs/News.html What's New == News since 0.7.6 Bug Fixes - * Fixed a bug in SQLRelatedJoin that ignored per-instance connection. * Fixed a bug in MySQL connection in case there is no charset in the DB URI. For a more complete list, please see the news: http://sqlobject.org/docs/News.html Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list
Re: Designing a graph study program
andrea <[EMAIL PROTECTED]> writes: > On 9 Mag, 09:10, Alexander Schliep <[EMAIL PROTECTED]> wrote: >> Check outhttp://gato.sf.net(LGPL license). It does exactly what you >> want to do and there is a binary for MacOS X. Algorithms are implemented >> using Gato's graph class and rudimentary visualizations you get for free >> by replacing standard data structures (e.g., a vertex queue) by >> animated ones (AnimatedVertexQueue). >> > Very very nice well done! Thanks. > I'd like to do something similar, just to learn something new... Gato is open source and I'd be happy to collaborate. There are quite a few areas (e.g. SVG export, displays for data structure contents, more complete 3D support, polygon edges, running backwards?) which need work. > Could you explain me how you designed it?? How is the step mechanism > done?? The algorithm is executed by a subclass of the Python debugger (see Gato.py). A Tk event mechanism is used to step to the next line if you are in running mode. Otherwise the user steps manually. The visualizations are done with animated data structures, which animate changes to their internal state with respect to the graph: e.g., when you add or remove v to/from an AnimatedVertexQueue it changes v's color. Tk has a canvas which does object-oriented drawing. A line is not just a bunch of pixels but rather an object which you can move, scale, has callbacks. I dislike Tcl, but Tk is amazing, even it it looks 1980s. There is a paper http://algorithmics.molgen.mpg.de/preprints/2000-CATBox-MTCM.pdf describing the ideas. Best, Alexander -- http://mail.python.org/mailman/listinfo/python-list
SQLObject 0.8.4
Hello! I'm pleased to announce the 0.8.4 release of SQLObject. What is SQLObject = SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject == Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.8.4 News and changes: http://sqlobject.org/News.html What's New == News since 0.8.3 Bug Fixes - * Fixed a bug in SQLRelatedJoin that ignored per-instance connection. * Fixed a bug in MySQL connection in case there is no charset in the DB URI. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list
Re: preferred windows text editor?
On May 10, 9:59 am, Charles Sanders <[EMAIL PROTECTED]> wrote: > Ant wrote: > > > What method of executing code snippets in a Python shell do other Vim > > users use? Other than just copy/paste? > > Not vim, but good old vi so should work in vim > > 1. Mark the start of the fragment, for exampls ms (to mark > with label s). Labels a through z are available. > 2. Move to the end of the fragment. > 3. :'s,.w !python to send the fragment to the python > interpreter Yes - that works nicely for code snippets in isolation. My quest for tighter integration of the Python console/IPython and vim will have to continue... -- Ant... http://antroy.blogspot.com/ -- http://mail.python.org/mailman/listinfo/python-list
SQLObject 0.9.0
Hello! I'm pleased to announce the 0.9.0 release of SQLObject, the first stable release of the 0.9 branch. What is SQLObject = SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject == Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.0 News and changes: http://sqlobject.org/News.html What's New == Features & Interface * Support for Python 2.2 has been declared obsolete. * Removed actively deprecated attributes; lowered deprecation level for other attributes to be removed after 0.9. * SQLite connection got columnsFromSchema(). Now all connections fully support fromDatabase. There are two version of columnsFromSchema() for SQLite - one parses the result of "SELECT sql FROM sqlite_master" and the other uses "PRAGMA table_info"; the user can choose one over the other by using "use_table_info" parameter in DB URI; default is False as the pragma is available only in the later versions of SQLite. * Changed connection.delColumn(): the first argument is sqlmeta, not tableName (required for SQLite). * SQLite connection got delColumn(). Now all connections fully support delColumn(). As SQLite backend doesn't implement "ALTER TABLE DROP COLUMN" delColumn() is implemented by creating a new table without the column, copying all data, dropping the original table and renaming the new table. * Versioning - see http://sqlobject.org/Versioning.html * MySQLConnection got new keyword "conv" - a list of custom converters. * Use logging if it's available and is configured via DB URI. * New columns: TimestampCol to support MySQL TIMESTAMP type; SetCol to support MySQL SET type; TinyIntCol for TINYINT; SmallIntCol for SMALLINT; MediumIntCol for MEDIUMINT; BigIntCol for BIGINT. Small Features -- * Support for MySQL INT type attributes: UNSIGNED, ZEROFILL. * Support for DEFAULT SQL attribute via defaultSQL keyword argument. * cls.tableExists() as a shortcut for conn.tableExists(cls.sqlmeta.table). * cls.deleteMany(), cls.deleteBy(). Bug Fixes - * idName can be inherited from the parent sqlmeta class. * Fixed a longstanding bug with .select() ignoring 'limit' parameter. * Fixed a bug with absent comma in JOINs. * Fixed sqlbuilder - .startswith(), .endswith() and .contains() assumed their parameter must be a string; now you can pass an SQLExpression: Table.q.name.contains(func.upper('a')), for example. * Fixed a longstanding bug in sqlbuilder.Select() with groupBy being a sequence. * Fixed a bug with Aliases in JOINs. * Yet another patch to properly initialize MySQL connection encoding. * Fixed a minor comparison problem in test_decimal.py. * Fixed a bug in SQLRelatedJoin that ignored per-instance connection. Docs * Added documentation about 'validator' Col constructor option. * Added an answer and examples to the FAQ on how to use sqlmeta.createSQL. * Added an example on how to configure logging. * More documentation about orderBy. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED] Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list
RE: keyword checker - keyword.kwlist
> From: [EMAIL PROTECTED] > > Hi > > I try to check whether a given input is keyword or not. However this > script won't identify keyword input as a keyword. How should I modify it > to make it work? > > #!usr/bin/env python > import keyword > > input = raw_input('Enter identifier to check >> ') > if input in keyword.kwlist: > print input + "is keyword" > > else: > print input + "is not keyword" It works fine for me. Well, it did once I realized that 'keyword.py' was not a good name to save the file under. --- -Bill Hamilton -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble with generators
Hans-Peter Jansen schrieb: > Hi Pythonistas, > > I'm stuck in a maze of new style classes and generators. While I love the > concepts, I obviously didn't grok them throughout. > > I'm trying to generate a bunch of similar classes, where some are contained > in list attributes of others, e.g.: All your code below shows that you don't create classes, but _instances_ of classes. So - is that what you mean to do? Or do you really want to create classes? > class A: > def __init__(self): > self.id = 'A1' > self.b = [instances of B] > > class B: > def __init__(self): > self.id = 'B1' > > Here's the test code, I have: > > #!/usr/bin/env python > # -*- coding: utf8 -*- > > class A(object): > "A" > def __init__(self): > self.id = None > self.b = [] > > class B(object): > "B" > def __init__(self): > self.id = None > > class Gen(object): > def records(self, cls): > for i in range(3): > setattr(cls, "id", "%s%s" % (cls.__doc__, i)) > yield cls > > def display(self, rec): > for i in rec.__dict__.keys(): > if not i.startswith("_"): > print "%s: %s: %s" % (rec.__doc__, i, rec.__dict__[i]) > > class GenA(Gen): > def __init__(self): > self.genB = GenB() > > def records(self): > for a in Gen.records(self, A()): Here you pass an instance of A, not the class A. > for b in self.genB.records(): > #self.genB.display(b) > a.b.append(b) > #self.display(a) > yield a > > class GenB(Gen): > def records(self): > return Gen.records(self, B()) Same here - instance of B. > # testing.. > > aRecs = [] > bRecs = [] > > for i, r in enumerate(GenB().records()): > bRecs.append(r) > print i, r.id, r > > for i, r in enumerate(GenA().records()): > aRecs.append(r) > print i, r.id, r > for b in r.b: > print b.id, b > > > Here's the commented output: > # even if I keep a reference to each rec, the object is reused: > 0 B0 <__main__.B object at 0xb7bd0f8c> > 1 B1 <__main__.B object at 0xb7bd0f8c> > 2 B2 <__main__.B object at 0xb7bd0f8c> Sure - because you create one B-instance, and pass that to your generator. That generator then simply sets the succinct id's on that object, and returns it. But it is always the same instance!! In a nutshell, you do this: b = B() res = [] for i in xrange(3): b.id = i res.append(b) Always the same b. What you seem to want is this >>> class B(object): ...pass ... >>> res = [] >>> for i in xrange(3): ... class BSubClass(B): ... pass ... BSubClass.id = i ... res.append(BSubClass) ... >>> print [c.id for c in res] [0, 1, 2] >>> > # same here, with additional quadratic behavior, I do not understand > 0 A0 <__main__.A object at 0xb7bd206c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd210c> > 1 A1 <__main__.A object at 0xb7bd206c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd20ec> > B2 <__main__.B object at 0xb7bd20ec> > B2 <__main__.B object at 0xb7bd20ec> > 2 A2 <__main__.A object at 0xb7bd206c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd210c> > B2 <__main__.B object at 0xb7bd20ec> > B2 <__main__.B object at 0xb7bd20ec> > B2 <__main__.B object at 0xb7bd20ec> > B2 <__main__.B object at 0xb7bd0f8c> > B2 <__main__.B object at 0xb7bd0f8c> > B2 <__main__.B object at 0xb7bd0f8c> It's not quadratic - you add the same B to a.b in each generator run, so the first run shows 3 times the B, then 6, then 9. And because its always the same instance, printing them yields the same id for all - B2. > I expected to get 3 different class objects from both sections, with each A > containing 3 different Bs in the latter section, but obviously got > something else. > > Could some kind soul help me to distangle my mind twist here? Am I healable? I'm still not sure what you want - do you want instances created, or classes? For the former, you need constructor calls on your classes, and pass the class instead of an instance. Like this: class B(object): pass def g(cls): for i in xrange(3): o = cls() o.id = i yield o list(g(B)) Or you want really different classes (which is somewhat strange then to create that hierarchy of yours with As containing Bs), which you can accomplish using a class-statement in the generator as shown above. There are other ways as well, but less intuitive I'd say. Maybe stepping back and telling us what you want to accomplish here would help Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble with generators
In <[EMAIL PROTECTED]>, Hans-Peter Jansen wrote: > class Gen(object): > def records(self, cls): > for i in range(3): > setattr(cls, "id", "%s%s" % (cls.__doc__, i)) > yield cls > > […] > > class GenA(Gen): > def __init__(self): > self.genB = GenB() > > def records(self): > for a in Gen.records(self, A()): Here you create an instance of `A` and pass that *instance* and not the *class*. If you would pass the class here, you must create objects in `Gen.records()`. Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list
ANN: eGenix mx Base Distribution 3.0.0 (mxDateTime, mxTextTools, etc.)
ANNOUNCING eGenix.com mx Base Extension Package Version 3.0.0 Open Source Python extensions providing important and useful services for Python programmers. This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mx-Base-Distribution-3.0-GA.html ABOUT The eGenix.com mx Base Extensions for Python are a collection of professional quality software tools which enhance Python's usability in many important areas such as fast text searching, date/time processing and high speed data types. The tools have a proven record of being portable across many Unix and Windows platforms. You can write applications which use the tools on Windows and then run them on Unix platforms without change due to the consistent platform independent interfaces. All available packages have proven their stability and usefulness in many mission critical applications and various commercial settings all around the world. * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). NEWS The 3.0 release of the eGenix mx Base Distributions comes with a huge number of enhancements, bug fixes and additions. Some highlights: * All mx Extensions have been ported to Python 2.5. * mxDateTime has support for working with Python's datetime module types, so you can use and combine both if necessary. The parser was enhanced to support even more formats and make it more reliable than ever before. * mxTextTools now fully supports Unicode, so you can parse Unicode data just as fast as you can 8-bit string data. The package also includes a tag table compiler and new jump target support to simplify working with tag tables. * mxURL and mxUID were previously released as part of our mx Experimental distribution. They have now been integrated into the base distribution, providing easy-to-use data types for common tasks in web programming. * We've switched from the old distutils wininst installer to the new MSI installer for the Windows Python 2.5 build. This gives you a lot more options for automatic installs, including unattended installs. See http://www.python.org/download/releases/2.5/msi/ for details. For a more detailed description of changes, please see the respective package documentation on our web-site. As always we are providing pre-compiled versions of the package for Windows, Linux, Mac OS X, FreeBSD and Solaris as well as sources which allow you to install the package on all other supported platforms. DOWNLOADS The download archives and instructions for installing the packages can be found on the eGenix mx Base Distribution page: http://www.egenix.com/products/python/mxBase/ UPGRADING Please note that the 2.0 series of the eGenix mx Base Distribution does not support Python 2.5 on 64-bit platforms due to the Py_ssize_t changes in the Python C API. You are encouraged to upgrade to the new 3.0 series, if you plan to deploy on 64-bit platforms and use Python 2.5 as basis for your applications. LICENSES & COSTS The eGenix mx Base package is distributed under the eGenix.com Public License which is a CNRI Python License style Open Source license. You can use the package in both commercial and non-commercial settings without fee or charge. The package comes with full source code SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, May 10 2007) >>> Python/Zope Consulting and Support ...http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/
ANN: eGenix mxODBC Distribution 3.0.0 (mxODBC Database Interface)
ANNOUNCING eGenix.com mxODBC Database Interface Version 3.0.0 Our commercially supported Python extension providing ODBC database connectivity to Python applications on Windows and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-mxODBC-Distribution-3.0-GA.html ABOUT The mxODBC Database Interface allows users to easily connect Python applications to just about any database on the market today - on both Windows and Unix platforms in a highly portable and convenient way. This makes mxODBC the ideal basis for writing cross-platform database programs and utilities in Python. mxODBC is included in the eGenix.com mxODBC Distribution for Python, a commercial part of the eGenix.com mx Extension Series, a collection of professional quality software tools which enhance Python's usability in many important areas such as ODBC database connectivity, fast text processing, date/time processing and web site programming. The package has proven its stability and usefulness in many mission critical applications and various commercial settings all around the world. * About Python: Python is an object-oriented Open Source programming language which runs on all modern platforms (http://www.python.org/). By integrating ease-of-use, clarity in coding, enterprise application connectivity and rapid application design, Python establishes an ideal programming platform for todays IT challenges. * About eGenix: eGenix is a consulting and software product company focused on providing professional quality services and products to Python users and developers (http://www.egenix.com/). NEWS mxODBC 3.0 has received a large number of enhancements and supports more ODBC drivers than ever. Some highlights: * mxODBC has been ported to Python 2.5. * We've worked a lot on the Unicode support and made it more robust, especially on Unix platforms where the ODBC Unicode support has stabilized over the last few years. You can now issue commands using Unicode and exchange Unicode data with the database in various configurable ways. * We've also added a methods to give you more control of the connections and cursors as well as the .callproc() method for calling stored procedures that mxODBC 2.0 was missing. * Multiple result sets via the .nextset() are also supported, so working with stored procedures should be a lot easier now. * Another highlight is the added support for Python's datetime module types and the option to use strings for date/time processing (e.g. to be able to use timezones in timestamps if that's supported by the database). * Python's decimal module is now supported as well and it's possible to configure mxODBC to return Decimal types for numeric values. * mxODBC 3.0 received full 64-bit support, so that you can run mxODBC (and all other mx Extensions) on e.g. AMD64 platforms. * We've switched from the old distutils wininst installer to the new MSI installer for the Windows Python 2.5 build. This gives you a lot more options for automatic installs, including unattended installs. See http://www.python.org/download/releases/2.5/msi/ for details. Note that in order to avoid confusion, we've decided to rename the eGenix.com mx Commercial Distribution to eGenix.com mxODBC Distribution with this release. The commercial distribution has always only contained the mxODBC package, so this was an obvious step to clarify things for our users. As always we are providing pre-compiled versions of the package for Windows, Linux, Mac OS X, FreeBSD and Solaris as well as sources which allow you to install the package on all other supported platforms. DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/mxODBC/ IMPORTANT: In order to use the eGenix mx Commercial package you will first need to install the eGenix mx Base package which can be downloaded from here: http://www.egenix.com/products/python/mxBase/ UPGRADING Please note that mxODBC 2.0 does not support Python 2.5 on 64-bit platforms due to the Py_ssize_t changes in the Python C API. You are encouraged to upgrade to the new mxODBC 3.0 release, if you plan to deploy on 64-bit platforms and use Python 2.5 as basis for your applications. LICENSES & COSTS This release br
Re: keyword checker - keyword.kwlist
On Thu, 10 May 2007 13:38:40 +, tom wrote: > Hi > > I try to check whether a given input is keyword or not. However this > script won't identify keyword input as a keyword. How should I modify it > to make it work? It works for me. Try printing keyword.__file__ to make sure you are importing the right file. Also try printing keyword.kwlist. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list
Re: keyword checker - keyword.kwlist
In article <[EMAIL PROTECTED]>, <[EMAIL PROTECTED]> wrote: [ ... ] >> Try to change the 'input' variable name with other... >Changed input variable to myInput, but the result is still the same. That was good advice, but isn't going to help here. Because "input" isn't a keyword, it's a builtin. If you want to check builtins as well as keywords, you need >>> if myInput in keyword.kwlist + dir(__builtins__): (Although obviously you'd pre-build that list.) >for example, 'else' isn't identified as a keyword by the script though >it exists in keyword.kwlist. ? >>> def check(): ... input = raw_input('Enter identifier to check >> ') ... if input in keyword.kwlist: ... print input, "is keyword" ... else: ... print input, "is not keyword" ... Enter identifier to check >> input input is not keyword >>> check() Enter identifier to check >> else else is keyword >>> -- \S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump -- http://mail.python.org/mailman/listinfo/python-list
Re: keyword checker - keyword.kwlist
Still no go. I just can't get it right. My current script: #!usr/bin/env python import keyword myInput = raw_input('Enter identifier to check >> ') if myInput in keyword.kwlist: print myInput, "is keyword" else: print myInput, "is not keyword" print keyword.kwlist print keyword.__file__ And the output: Enter identifier to check >> else else is not keyword ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] F:\Ohjelmat\Python25\Lib\keyword.pyc -- http://mail.python.org/mailman/listinfo/python-list
Newbie look at Python and OO
I learned to program with Pascal, way back when. Went into software development for a while, then went into systems admin. Have programmed in several languages, just learning Python. Some things I find odd: 1) 5/-2 == -3? 2) list assignment handling, pointing two vars to the same list: With simple data types: >>> a = 5 >>> b = a >>> a = 3 >>> a,b (3, 5) Which is what I'd expect, since I have changed a, but not b. But with lists: >>> a = list("1234") >>> b = a >>> a.append("5") >>> a,b (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) b changes even though I have not touched b. I know why, but this is not what I would ordinarilly expect, it does not seem intuitive. And, IMO, it gets worse: >>> a = list("1234") >>> b = a >>> a = a + ['5'] >>> a,b (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) Sometimes changing a changes b, and sometimes not. You also have to remember that subseqent changes to a will not change b - after some operation but not others. To those who think in Python, I'm sure this all seems normal. But, having programmed in about one dozen other language, this seems downright bizare to me. I know why it works like this, but it seems like an odd way to do things. 3) ambiguous use of the form: this.that() Sometimes, this.that() means module.funcion() as in: >>> os.dirlist(".") Other times, "this" is sort of like a parameter to the "that" function: >>> a = list("1234") >>> "_".join(a) '1_2_3_4_5' And still other times, is seems that "this" is an object, acted upon by "that" : >>> a = list("1234") >>> b = "_".join(a) >>> b.split("_") ['1', '2', '3', '4', '5'] BTW: it seems a bit odd to that the positions of the string, and the delimitor, are reversed between the complementory functions join(), and split(). I suppose if it weren't for OO, we have something terribly complicated, like: split(str, "_") join(str, "_") Again, those who think in Python, will understand right away that: math.count(x) is counting the substring "x" in the "math" string. But can you see where that might be confused to be a function called count() in the math module? I'm not complaining. Python is a great language in many respects. But, I would take some issue with those claiming Python is intuitive and easy. IMO: there seems to be many ambiguous, unintuitve, and confusing, aspects to Python. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie look at Python and OO
On Thu, 2007-05-10 at 08:58 -0700, walterbyrd wrote: > I learned to program with Pascal, way back when. Went into software > development for a while, then went into systems admin. Have programmed > in several languages, just learning Python. > > Some things I find odd: > > 1) 5/-2 == -3? Division of integers performs a "floor division" that rounds the result down to a whole number. If you want a floating point result, you'll need to specify that you're working with floats: 5.0/-2 or float(5)/-2 > 2) list assignment handling, pointing two vars to the same list: See http://effbot.org/zone/python-objects.htm . > 3) ambiguous use of the form: this.that() The form "this.that" *always* means the same: It refers to the attribute called "that" of the object called "this". This may yield seemingly different meanings depending on what type of object "this" is, but the basic mechanism is always the same. The main source of your confusion seems to stem from the fact that join() was decided somewhat non-intuitively to be a method of string instances. By the way, the next time you have a number of unrelated questions, please consider posting them in separate messages. That allows you to pick a more descriptive subject line for each message, and it makes the ensuing conversations easier to follow. Best regards, -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie look at Python and OO
On 2007-05-10, walterbyrd <[EMAIL PROTECTED]> wrote: > 2) list assignment handling, pointing two vars to the same list: Python doesn't have variables. It has objects to which you can bind names. > But with lists: a = list("1234") That creates a list object and binds the name "a" to it. b = a That binds the name b to that same object. You now have two names bound a single object. a.append("5") Now you modify that object. a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. You modified the object to which the name "b" is bound. > I know why, but this is not what I would ordinarilly expect, Stop thinking in "C". ;) > it does not seem intuitive. When one attempts to use intuition devloped in one environment in a different environment it is often wrong. That's why brains have capability to change. > And, > IMO, it gets worse: > a = list("1234") b = a Again, you have a single object to which both names "a" and "b" are bound. a = a + ['5'] Now you've created a new object and bound the name "a" to it. You now have two objects and the name "b" is still bound to the original one. a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) > Sometimes changing a changes b, and sometimes not. You're thinking wrongly. Start thinking about objects/names and not about "variables". > You also have to remember that subseqent changes to a will not > change b - after some operation but not others. To those who > think in Python, I'm sure this all seems normal. Yes, it does. > But, having programmed in about one dozen other language, this > seems downright bizare to me. I know why it works like this, > but it seems like an odd way to do things. If those dozen other languages all used the "variable" paradigm (fixed regions of storage with fixed names) rather than the object/name binding paradigm, then yes, it probably seems like an odd way to do things. If you grew up using base-12, then base-10 seems like an odd way to do things. > 3) ambiguous use of the form: this.that() Nope, it always means exactly the same thing: look up the "that" attribute of object "this", and then call it. Are you confused by the fact that modules are objects? > Sometimes, this.that() means module.funcion() as in: > os.dirlist(".") Call the "dirlist" attribute of the object to which the name "os" is bound. > Other times, "this" is sort of like a parameter to the "that" > function: > a = list("1234") "_".join(a) > '1_2_3_4_5' Call the "join" attribute of the anonymous string object "_". > And still other times, is seems that "this" is an object, acted upon > by "that" : > a = list("1234") b = "_".join(a) b.split("_") > ['1', '2', '3', '4', '5'] Call the "split" attribute of the object to which the name "b" is bound. > Again, those who think in Python, will understand right away that: > > math.count(x) > > is counting the substring "x" in the "math" string. No, that isn't obvious at all unless we've previously been told that the name "math" is bound to a string object and we happen to know that a string object's "count" attribute is a bound method that counts occurances of the passed substring. > But can you see where that might be confused to be a function > called count() in the math module? A python programmer would think that it's calling the "count" attribute of whatever the name "math" is bound to. The name "math" might be bound to a module, a string, or some other type of object. > I'm not complaining. Python is a great language in many > respects. But, I would take some issue with those claiming > Python is intuitive and easy. Unlearning old habits is always difficult. > IMO: there seems to be many ambiguous, unintuitve, and > confusing, aspects to Python. Certainly if you're thinking about it using the wrong set of concepts. -- Grant Edwards grante Yow! I'm continually AMAZED at at th'breathtaking effects visi.comof WIND EROSION!! -- http://mail.python.org/mailman/listinfo/python-list
Re: change of random state when pyc created??
Alan Isaac wrote: > "Carsten Haese" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> I was simply pointing out all the ways in which you made it difficult for > the >> community to explain your problem. > > And without that community, I would still not have a clue. > Thanks to all! > >> Please feel free to suggest specific wording changes to make the > documentation >> more useful. > > I'm sure my first pass will be flawed, but here goes: > > http://docs.python.org/lib/typesmapping.html: > to footnote (3), add phrase "which may depend on the memory location of the > keys" to get: > > Keys and values are listed in an arbitrary order, > which may depend on the memory location of the keys. > This order is non-random, varies across Python implementations, > and depends on the dictionary's history of insertions and deletions. > > http://docs.python.org/lib/types-set.html: append a new sentence to 2nd > paragraph > > Iteration over a set returns elements in an arbitrary order, > which may depend on the memory location of the elements. It's misleading. It only depends on the memory location of the elements if __hash__() is implemented as id() (the default). How about this? """Never rely on the order of dictionaries and sets.""" -- 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: Newbie look at Python and OO
On 10 May 2007 08:58:54 -0700, walterbyrd <[EMAIL PROTECTED]> wrote: > I learned to program with Pascal, way back when. Went into software > development for a while, then went into systems admin. Have programmed > in several languages, just learning Python. > > Some things I find odd: > > 1) 5/-2 == -3? > Integer division. A gotcha, I grant you. Fixable with a __future__ import which will become the default soonish. > 2) list assignment handling, pointing two vars to the same list: > > With simple data types: > >>> a = 5 > >>> b = a > >>> a = 3 > >>> a,b > (3, 5) > > Which is what I'd expect, since I have changed a, but not b. > > But with lists: > >>> a = list("1234") > >>> b = a > >>> a.append("5") > >>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. I know why, but this is > not what I would ordinarilly expect, it does not seem intuitive. And, > IMO, it gets worse: > I don't like the word "intuitive", because it's meaningless. Something intuitive is something that you already know. You're taking a model of variables and references from another language, and assuming Python works the same way when it doesn't. There's no good reason to assume this, and it's well documented that you shouldn't. The problem comes when people try to teach Python by telling you it's "pass by reference" or "it's like a pointer" - it's not, and you need to be taught how it *actually* works, which isn't especially complicated (easier to grasp than pointers, in my experience). > >>> a = list("1234") > >>> b = a > >>> a = a + ['5'] > >>> a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) > > Sometimes changing a changes b, and sometimes not. You also have to > remember that subseqent changes to a will not change b - after some > operation but not others. To those who think in Python, I'm sure this > all seems normal. But, having programmed in about one dozen other > language, this seems downright bizare to me. I know why it works like > this, but it seems like an odd way to do things. > You have to disabuse yourself of the idea that assignment and "changing" are the same thing. People without previous programming experience rarely stumble on this particular hurdle. > 3) ambiguous use of the form: this.that() > > Sometimes, this.that() means module.funcion() as in: > > >>> os.dirlist(".") > > Other times, "this" is sort of like a parameter to the "that" > function: > this.that() is *always* looking up "that" in "this" and calling it. It never does anything else. What "that" you get depends on what "this" is, and I don't know how you could ever expect anything else. > >>> a = list("1234") > >>> "_".join(a) > '1_2_3_4_5' > > And still other times, is seems that "this" is an object, acted upon > by "that" : > > >>> a = list("1234") > >>> b = "_".join(a) > >>> b.split("_") > ['1', '2', '3', '4', '5'] > > BTW: it seems a bit odd to that the positions of the string, and the > delimitor, are reversed between the complementory functions join(), > and split(). I suppose if it weren't for OO, we have something > terribly complicated, like: > > split(str, "_") > join(str, "_") > Join takes a iterable, not a string. It's "reversed" from what you might expect so that it can generically work over any sort of sequence or iterable. > Again, those who think in Python, will understand right away that: > > math.count(x) > > is counting the substring "x" in the "math" string. But can you see > where that might be confused to be a function called count() in the > math module? > This is a good reason not to give a variable which contains a string a name like "math". The language can't protect you from this, and how would you expect it to? Obviously, especially as the standard lib grows, it can be difficult to avoid these sorts of name collisions. But context is everything and in well written code it shouldn't be hard to disambiguate these sort of things. > I'm not complaining. Python is a great language in many respects. But, > I would take some issue with those claiming Python is intuitive and > easy. IMO: there seems to be many ambiguous, unintuitve, and > confusing, aspects to Python. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie look at Python and OO
walterbyrd wrote: > I learned to program with Pascal, way back when. Went into software > development for a while, then went into systems admin. Have programmed > in several languages, just learning Python. > > Some things I find odd: > > 1) 5/-2 == -3? > > 2) list assignment handling, pointing two vars to the same list: > > With simple data types: a = 5 b = a a = 3 a,b > (3, 5) > > Which is what I'd expect, since I have changed a, but not b. > > But with lists: a = list("1234") b = a a.append("5") a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. I know why, but this is > not what I would ordinarilly expect, it does not seem intuitive. And, > IMO, it gets worse: > a = list("1234") b = a a = a + ['5'] a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) > > Sometimes changing a changes b, and sometimes not. You also have to > remember that subseqent changes to a will not change b - after some > operation but not others. To those who think in Python, I'm sure this > all seems normal. But, having programmed in about one dozen other > language, this seems downright bizare to me. I know why it works like > this, but it seems like an odd way to do things. > > 3) ambiguous use of the form: this.that() > > Sometimes, this.that() means module.funcion() as in: > os.dirlist(".") > > Other times, "this" is sort of like a parameter to the "that" > function: > a = list("1234") "_".join(a) > '1_2_3_4_5' > > And still other times, is seems that "this" is an object, acted upon > by "that" : > a = list("1234") b = "_".join(a) b.split("_") > ['1', '2', '3', '4', '5'] > > BTW: it seems a bit odd to that the positions of the string, and the > delimitor, are reversed between the complementory functions join(), > and split(). I suppose if it weren't for OO, we have something > terribly complicated, like: > > split(str, "_") > join(str, "_") > > Again, those who think in Python, will understand right away that: > > math.count(x) > > is counting the substring "x" in the "math" string. But can you see > where that might be confused to be a function called count() in the > math module? > > I'm not complaining. Python is a great language in many respects. But, > I would take some issue with those claiming Python is intuitive and > easy. IMO: there seems to be many ambiguous, unintuitve, and > confusing, aspects to Python. > Some of your confusion is because you have ingrained ideas about how "other" languages handle things and want Python to do it the same way. Give it some time and you will begin to understand (as many have) that there REALLY is method to the apparent madness... > Some things I find odd: > > 1) 5/-2 == -3? > > What do you except from integer arithmetic? The ONLY possible answers are -2, or -3. Python chooses to always return the floor (lower) of the two values in integer division. While this makes complete sense for positive integers, it seems odd for negative ones, but it is consistent. > With simple data types: a = 5 b = a a = 3 a,b > (3, 5) > Here you confuse Python's complete object orientation with other previously learned languages. a=5 In python means: make me a name 'a' in the local namespace that points to an object that holds a 5. It does not mean: create a memory area referred to by a and place a 5 in it (as many other languages do). b=a In python means: make me a name 'b' in the local namespace that points to object 'a'. A good way to see this is to do: id(a) id(b) you will see that they both point to the same object. > Which is what I'd expect, since I have changed a, but not b. > > But with lists: a = list("1234") b = a a.append("5") a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. I know why, but this is > not what I would ordinarilly expect, it does not seem intuitive. And, > IMO, it gets worse: > Again this is because of objects not "containers" like Pascal or other languages. b=a In python means: create me an object 'b' that points the same place as object 'a'. a.append("5") modifies both variables because both variables point to the same place. a = list("1234") b = a a = a + ['5'] a,b > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) > > Sometimes changing a changes b, and sometimes not. You also have to > remember that subseqent changes to a will not change b - after some > operation but not others. To those who think in Python, I'm sure this > all seems normal. But, having programmed in about one dozen other > language, this seems downright bizare to me. I know why it works like > this, but it seems like an odd way to do things. > do >>> id(a) 18192784 >>> id(b) 18192784 >>> a=a+['5'] In python means: create a new object a that is the old object a with a '5' appended to the
Re: replacing string in xml file--revisited
On May 10, 4:21 am, [EMAIL PROTECTED] wrote: > On May 10, 1:55 pm, [EMAIL PROTECTED] wrote: > > > > > On May 10, 12:56 am, [EMAIL PROTECTED] wrote: > > > > Hi, > > > I need to replace a string in xml file with something else.Ex > > > > - > > > rate > > > rate > > > > > > > > > > > > - > > > > Here i have opened an xml > > > file(small part is pasted here).I want to replace the word 'localId' > > > with 'dataPackageID' wherever it comes in xml file.I have asked this > > > before and got a code: > > > input_file = open(filename) > > > xmlcontents = input_file.read() > > > input_file.close() > > > xmlcontents = xmlcontents.replace("spam", "eggs") > > > output_file = open(filename,"w") > > > output_file.write(xmlcontents) > > > output_file.close() > > > > Although this works alone it is nto > > > working when i handle multiple file I/O.Is there a alternative to do > > > this.(maybe without read() operation) > > > Thanks > > > After reading your post again, this might be better: > > > #!/usr/bin/env python > > > from elementtree import ElementTree as et > > tree = et.parse("testxml.xml") > > > for t in tree.getiterator("SERVICEPARAMETER"): > > if t.get("Semantics") == "localId": > > t.set("Semantics", "dataPackageID") > > > tree.write("output.xml") > > > ~Sean- Hide quoted text - > > > - Show quoted text - > > which module should be imported for above to work,it says > ImportError: No module named elementtree > Thanks You can either 1) upgrade to python 2.5 which includes the elementtree module or 2) download and add the module to your current installation http://effbot.org/zone/element-index.htm ~Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie look at Python and OO
On May 10, 11:58 am, walterbyrd <[EMAIL PROTECTED]> wrote: >[snip] > > 2) list assignment handling, pointing two vars to the same list: > > With simple data types:>>> a = 5 > >>> b = a > >>> a = 3 > >>> a,b > > (3, 5) > > Which is what I'd expect, since I have changed a, but not b. > > But with lists:>>> a = list("1234") > >>> b = a > >>> a.append("5") > >>> a,b > > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4', '5']) > > b changes even though I have not touched b. I know why, but this is > not what I would ordinarilly expect, it does not seem intuitive. Well, although it may not be what you expect right now, it *is* quite uniform with the rest of the language. That is: labels refer to objects. Writing ``a = b`` just makes the 'b' label refer to the same thing that the 'a' label refers to. Nice and simple. > And, > IMO, it gets worse: > > >>> a = list("1234") > >>> b = a > >>> a = a + ['5'] > >>> a,b > > (['1', '2', '3', '4', '5'], ['1', '2', '3', '4']) Now here, after you've set 'a' and 'b' to refer to the same object, you went and created a new object (a + ['5']) for a to refer to. ``a + ['5']`` creates a new object, whereas ``a.append('5')`` just modifies the existing object. (By the way, as an aside, '5' is a one-character string, not a number.) > [snip] > > 3) ambiguous use of the form: this.that() > > Sometimes, this.that() means module.funcion() as in: > > >>> os.dirlist(".") > > Other times, "this" is sort of like a parameter to the "that" > function: > > >>> a = list("1234") > >>> "_".join(a) > > '1_2_3_4_5' I think I see what you mean: In Python, there's this convention that you're supposed to name your classes starting with a capital letter (``class HeadCheese(object):``), but for core built-in classes, they start with a lower-case letter (like ``list``, ``dict``, ``set``, ``file``, etc.). So, ``list('foo')`` is actually a constructor call. Also, note that, in Python, "_" is a literal for creating a string object, so you can call methods on that resulting object -- as in ``'_'.join('cheezit')`` -- the same as if you'd said ``foo = "_"; foo.join('cheezit')``. > [snip] > > I'm not complaining. Python is a great language in many respects. But, > I would take some issue with those claiming Python is intuitive and > easy. IMO: there seems to be many ambiguous, unintuitve, and > confusing, aspects to Python. Well, every language has its warts. :) Folks are working to minimize or remove a number of them for Python 3000. ---John -- http://mail.python.org/mailman/listinfo/python-list
Re: change of random state when pyc created??
On Thu, 2007-05-10 at 11:29 -0500, Robert Kern wrote: > """Never rely on the order of dictionaries and sets.""" Easy, Robert, there's a baby in that bathwater. I think it's useful to note that the arbitrary ordering returned by dict.keys() et al. is locally stable in the absence of intervening modifications, as long as the guarantee is worded in a way that prevents overly optimistic reliance on that ordering. -Carsten -- http://mail.python.org/mailman/listinfo/python-list