odict the Ordered Diction 0.2.2
After a break of almost a year there has been an update to `odict the Ordered Dictionary http://www.voidspace.org.uk/python/odict.html`_. The latest version is 0.2.2, with changes implemented by Nicola Larosa. Despite over 700 downloads since May (plus 1300 as part of `pythonutils http://www.voidspace.org.uk/python/pythonutils.html`_) there have been no bug reports, only improvements [#]_. {sm;:-)} * `Quick Download http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=odict.py`_ What is odict? == **odict** is a pure Python implementation of an ordered dictionary. It keeps keys in insertion order and allows you to change the order. Methods (including iteration) that would return members in an arbitrary order are now ordered. There is also the `SequenceOrderedDict http://www.voidspace.org.uk/python/odict.html#sequenceordereddict`_ that behaves like a sequence as well as a dictionary. It allows slicing and the keys, values and items methods are special sequence objects (which are also callable and so behave as methods too). What's New ? == Code --- Removed the TODO and CHANGELOG sections in the tail docstring (they are in the docs anyway). Disabled warnings during tests. Explicitly disabled tests execution on Python v.2.2 . In addition to the slicing tests, other ones are failing. Removed code duplication between the ``__init__`` and the ``update`` methods. Misc. cleanup. Also, based on code from `Tim Wegener`_: - added the ``rename`` method; - removed a ``has_key`` usage in the ``__setitem__`` method. Documentation -- Moved the ISSUES chapter from code's tail docstring to here. Moved up the `Creating an Ordered Dictionary http://www.voidspace.org.uk/python/odict.html#creating-an-ordered-dictionary`_ chapter. Added prompts to the code examples and removed the superfluous print statements (sometimes they were there, sometimes they were not). Misc. cleanup. .. [#] So either no-one is using it, or it's really good... -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
ANN: FileTrack 0.1-beta3 is released
FileTrack is a Web-enabled communication log, keeping track of all of your company's inbound and outbound documents. It supports multiple logs, auto-archiving of older entries, and generates simple reports based on multiple criteria. One or more log entries, contacts, or documents can be grouped together into an issue for easier monitoring. This release of FileTrack is fully compatible with Porcupine v0.0.8. Moreover, it includes a few minor bug fixes and the UI has taken advantage of the new box layout QuiX widget, which has replaced the non-interactive splitters. This application is also a good sample for those willing to develop a Porcupine application, as it includes code for all of the three layers (custom schema, servlets and presentation) and all forms of servlets (PSP pages, XMLRPC and QuiX servlets). Installation instructions can be found at http://wiki.innoscript.org/index.php/Administrators/HowToInstallPPFiles Other available Porcupine applications can be downloaded from http://www.innoscript.org/component/option,com_remository/Itemid,33/func,selectcat/cat,4/ -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html
PIL throws exception when reading bitmap/pnm data
Hi all, I'm trying to extract the data from a bitmap or .pnm file using the following code: import Image img = Image.open(test.bmp,r) data=img.getdata() Unfortunately I get the following exception on Linux, but not on Windows: data=img.getdata() Traceback (most recent call last): File stdin, line 1, in module File /usr/local/lib/python2.5/site-packages/PIL/Image.py, line 796, in getdata self.load() File /usr/local/lib/python2.5/site-packages/PIL/ImageFile.py, line 147, in load self.map = mmap.mmap(file.fileno(), size) EnvironmentError: [Errno 19] No such device At this time, I cannot provide the full bitmap for copyright reasons, but I can provide some information about the bitmap: [EMAIL PROTECTED]:~$ file test.bmp test.bmp: PC bitmap data, Windows 3.x format, 1000 x 1000 x 8 The same code works for .ppm images in the same folder: [EMAIL PROTECTED]:~$ convert test.bmp test.ppm [EMAIL PROTECTED]:~$ python import Image img=Image.open(test.ppm) data=img.getdata() But does not work for .pnm images in the same folder: [EMAIL PROTECTED]:~$ convert test.bmp test.pnm [EMAIL PROTECTED]:~$ python import Image img=Image.open(test.pnm) data=img.getdata() Traceback (most recent call last): File stdin, line 1, in module File /usr/local/lib/python2.5/site-packages/PIL/Image.py, line 796, in getdata self.load() File /usr/local/lib/python2.5/site-packages/PIL/ImageFile.py, line 147, in load self.map = mmap.mmap(file.fileno(), size) EnvironmentError: [Errno 19] No such device PIL Version on Linux and Windows: $Id: Image.py 2337 2005-03-25 07:50:30Z fredrik $ How can I avoid this error without converting each image into a different format? Thanks and regards, Cameron. -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about import and sys.path
Frank Millman wrote: One small point. The docs have the following warning - Important: the caller is responsible for closing the file argument, if it was not None, even when an exception is raised. This is best done using a try ... finally statement. I have added this to my code. I wonder if you can avoid this in 2.5 by using the 'with' statement. I am still using 2.4, so I cannot test. Anyway, your suggestion does exactly what I want, and it works perfectly. Yes, of course. The `with` statement works exactly as previously try...finally. I've tried it in 2.5 and it works perfectly. You have to use `from __future__ import with_statement`, though. This statement will be always enabled in Python 2.6. -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading text labels from a Win32 window
[EMAIL PROTECTED] schrieb: [EMAIL PROTECTED] schrieb: Does anyone know of a way to read text labels from a Win32 application. I am familiar with using pywin32 and the SendMessage function to capture text from Buttons,text boxex, comboboxes, etc, however, the text I am would like to capture doesn't appear to be in a control. This article tells the whole story The secret life of GetWindowText http://blogs.msdn.com/oldnewthing/archive/2003/08/21/54675.aspx Appended is a script that is a fairly straight-forward conversion of the code in the above article to Python. Needs ctypes and comtypes. Python 2.5 already includes ctypes; comtypes can be installed with 'easy_install comtypes'. Thomas import sys, time from ctypes import windll, oledll, WinError, byref, POINTER from ctypes.wintypes import POINT from comtypes import COMError from comtypes.automation import VARIANT from comtypes.client import GetModule # create wrapper for the oleacc.dll type library GetModule(oleacc.dll) # import the interface we need from the wrapper from comtypes.gen.Accessibility import IAccessible def GetCursorPos(): Return the cursor coordinates pt = POINT() if not windll.user32.GetCursorPos(byref(pt)): raise WinError() return pt.x, pt.y def AccessibleObjectFromPoint(x, y): Return an accessible object and an index. See MSDN for details. pacc = POINTER(IAccessible)() var = VARIANT() oledll.oleacc.AccessibleObjectFromPoint(POINT(x, y), byref(pacc), byref(var)) return pacc, var if __name__ == __main__: while 1: time.sleep(1) x, y = GetCursorPos() try: pacc, index = AccessibleObjectFromPoint(x, y) name = pacc.accName[index] except (WindowsError, COMError), details: print details continue if name is not None: print ===, (x, y), = * 60 print name.encode(sys.stdout.encoding, backslashreplace) -- http://mail.python.org/mailman/listinfo/python-list
Re: Using SimpleXMLRPCServer in a Windows Service
At Tuesday 28/11/2006 05:49, Rudy Schockaert wrote: I found the problem. Actually both pieces of code work now. The problem was that when I run the SimpleXMLRPCService in a Windows Service, the STDERR needs to be redirected to a real file. I guess some kind of buffer overflow occurs when you don't do this. I added the following lines: snip def SvcStop(self): sys.stdout = self.stdout sys.stderr = self.stderr . def SvcDoRun(self): self.stdout = sys.stdout self.stderr = sys.stderr sys.stdout = file(c:/temp/my.log, a+, 0) sys.stderr = sys.stderr /snip Actually you don't have to restore the previous value; Python already saves the original value in sys.__stderr__ and restores it when program finishes. -- Gabriel Genellina Softlab SRL __ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ¡gratis! ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with imaplib (weird result if mailbox contains a %)
On 2006-11-28, Leo Kislov [EMAIL PROTECTED] wrote: Antoon Pardon wrote: This little program gives IMO a strange result. import imaplib user = cpapen cyr = imaplib.IMAP4(imap.vub.ac.be) cyr.login(cyrus, cOn-A1r) rc, lst = cyr.list('', user/%s/* % user) for el in lst: print %r % (el,) And the result is: '(\\HasNoChildren) / user/cpapen/Out' '(\\HasNoChildren) / user/cpapen/Punten' '(\\HasNoChildren) / user/cpapen/Spam' '(\\HasNoChildren) / user/cpapen/agoog to be' '(\\HasNoChildren) / user/cpapen/artistiek - kunst' '(\\HasNoChildren) / user/cpapen/copains et copinnes =x=' '(\\HasNoChildren) / user/cpapen/cp - writing' '(\\HasNoChildren) / user/cpapen/examen' '(\\HasNoChildren) / user/cpapen/important info (pass)' '(\\HasNoChildren) / user/cpapen/lesmateriaal' '(\\HasNoChildren) / user/cpapen/love - flesh for fantasy' '(\\HasNoChildren) / user/cpapen/media' '(\\HasNoChildren) / user/cpapen/music - beats' ('(\\HasNoChildren) / {25}', 'user/cpapen/newsletters %') '' '(\\HasNoChildren) / user/cpapen/organisatie - structuur' '(\\HasNoChildren) / user/cpapen/sociale wetenschappen' '(\\HasNoChildren) / user/cpapen/the closest ones to me [x]' '(\\HasNoChildren) / user/cpapen/vubrations' '(\\HasNoChildren) / user/cpapen/wm2addressbook' '(\\HasNoChildren) / user/cpapen/wm2prefs' '(\\HasNoChildren) / user/cpapen/wm2signature' What I have a problem with is the 14th and 15th line. All other entries are strings but the 14th is a tuple. and the 15th is an empty string. As far as I can tell every time a % is in the mailbox name I get this kind of result. I'm using python 2.3.3 and the imap sytem is Cyrus. Can someone explain what is going one? Is this a bug? Empty string seems to be a bug. But tuple is by design, read the docs and imap rfc. The protocol is convoluted in the first place, and so is python interface. Are there more docs than at http://www.python.org/doc/. I don't find those very helpfull in explaining this. I also took a look at rfc 2060 and to be honest I don't find anything there to explain this difference. I only took a closer look at section 7.2.2. So maybe I should look somewehere else but after reading section 7.2.2. I don't understand why the list method returned a tuple for this mailbox instead of the following string: '(\\HasNoChildren) / user/cpapen/newsletters %' If it is, is it fixed in later versions? Why don't you try to pull imaplib.py from later versions? I don't think it changed that much so it should be compatible with python 2.3 I could take my hands on a 2.4 version and the result was the same. Whether or not it is a bug, can I rely on the mailbox being the last item in the tuple in these cases? Yes (at least for list command) Well that is at least comforting. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
[PyQt] windows problem
Dumb question from extreme newbie. Steps so far: 1. Installed Python 2.5 2. Installed Qt 4.2.1 (with mingw) from executable 3. Installed PyQt 4.1 from executable Been trying to run the first example (t1.pyw) in the tutorials folder, but the following error pops up while running the from idle-python gui: Traceback (most recent call last): File C:/TestEnv/t1.pyw, line 7, in module from PyQt4 import QtGui ImportError: DLL load failed: The specified module could not be found. Thanks for any help! -henry -- http://mail.python.org/mailman/listinfo/python-list
Re: [PyQt] windows problem
On Wednesday 29 November 2006 8:12 am, [EMAIL PROTECTED] wrote: Dumb question from extreme newbie. Steps so far: 1. Installed Python 2.5 2. Installed Qt 4.2.1 (with mingw) from executable 3. Installed PyQt 4.1 from executable Been trying to run the first example (t1.pyw) in the tutorials folder, but the following error pops up while running the from idle-python gui: Traceback (most recent call last): File C:/TestEnv/t1.pyw, line 7, in module from PyQt4 import QtGui ImportError: DLL load failed: The specified module could not be found. Make sure your PATH includes the directories containing the Qt and MinGW DLLs. Phil -- http://mail.python.org/mailman/listinfo/python-list
Re: splitting a long string into a list
ronrsr wrote: still having a heckuva time with this. here's where it stand - the split function doesn't seem to work the way i expect it to. longkw1,type(longkw): Agricultural subsidies; Foreign aid;Agriculture; Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood Development, Birth Defects; type 'list' 1 longkw.replace(',',';') Agricultural subsidies; Foreign aid;Agriculture; Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood Development kw = longkw.split(; ,)#kw is now a list of len 1 kw,typekw= ['Agricultural subsidies; Foreign aid;Agriculture; Sustainable Agriculture - Support; Organic Agriculture; Pesticides, US, Childhood Development, Birth Defects; Toxic Chemicals;Antibiotics, Animals;Agricultural Subsidies what I would like is to break the string into a list of the delimited words, but have had no luck doing that - I thought split wuld do that, but it doens't. bests, -rsr- import SE# http://cheeseshop.python.org/pypi/SE/2.3 Split_Marker = SE.SE (' ,=| ;=| ')# Translates both ',' and ';' into an arbitrary split mark ('|') for item in Split_Marker (longstring).split ('|'): print item Agricultural subsidies Foreign aidAgriculture Sustainable Agriculture - Support Organic Agriculture ... etc. To get rid of the the leading space on some lines simply add corresponding replacements. SE does any number of substitutions in one pass. Defining them is a simple matter of writing them up in one single string from which the translator object is made: Split_Marker = SE.SE (' ,=| ;=| , =| ; =| ') for item in Split_Marker (longstring).split ('|'): print item Agricultural subsidies Foreign aidAgriculture Sustainable Agriculture - Support Organic Agriculture Regards Frederic -- http://mail.python.org/mailman/listinfo/python-list
Re: windows problem
thanks :)! On Nov 29, 12:35 am, Phil Thompson [EMAIL PROTECTED] wrote: On Wednesday 29 November 2006 8:12 am, [EMAIL PROTECTED] wrote: Dumb question from extreme newbie. Steps so far: 1. Installed Python 2.5 2. Installed Qt 4.2.1 (with mingw) from executable 3. Installed PyQt 4.1 from executable Been trying to run the first example (t1.pyw) in the tutorials folder, but the following error pops up while running the from idle-python gui: Traceback (most recent call last): File C:/TestEnv/t1.pyw, line 7, in module from PyQt4 import QtGui ImportError: DLL load failed: The specified module could not be found.Make sure your PATH includes the directories containing the Qt and MinGW DLLs. Phil -- http://mail.python.org/mailman/listinfo/python-list
Small prog question from a newbie: abt variables in a function definition
Hi all, I am a newbie as far as python is concerned ... I am trying to write a code for playing bridge in obj oriented manner .. Well ... i have this small problem: class hand: def __init__(self,set_of_cards=[]): self.set_of_cards=set_of_cards card_played_flag =0 def play(played_card): for i in self.set_of_cards: if self.set_of_cards[i] == played_card: self.set_of_cards.remove(played_card) def sort_hand(): for i in self.set_of_cards: for j in self.set_of_cards: if self.set_of_cards[j].faceself.set_of_cards[i].face self.set_of_cards[j],self.set_of_cards[i]=self.set_of_cards [i],self.set_of_cards[j] for i in self.set_of_cards: for j in self.set_of_cards: if self.set_of_cards[j].suitself.set_of_cards[i].suit self.set_of_cards[j],self.set_of_cards[i]=self.set_of_cards [i],self.set_of_cards[j] I have created card as a class with the attributes of suit face so .. card(suit,face) So my question is this --- The compiler doesnt recognise that there is self.set_of_cards[j] can be a card. It gives a syntax error. Also I have not created any instance of the class (Can that be a problem) So how do i fix this? Also can I specify that the list set_of_cards has only card objects? IF yes how? Thanks a lot. Shyam Sundar -- http://mail.python.org/mailman/listinfo/python-list
Re: Python program that validates an url against w3c markup validator
At Wednesday 29/11/2006 02:29, yaru22 wrote: I'd like to create a program that validates bunch of urls against the w3c markup validator (http://validator.w3.org/) and store the result in a file. Since I don't know network programming, I have no idea how to start coding this program. Why not use the standalone validator? You can download and install it. -- Gabriel Genellina Softlab SRL __ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ¡gratis! ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar -- http://mail.python.org/mailman/listinfo/python-list
Asyncore Medusa Example
Hi all does anyone know where you can find examples of how to write a native python webserver, I have looked at medusa and asyncore but there are no real examples and the doco is very light any help is appreciated regards graeme -- http://mail.python.org/mailman/listinfo/python-list
Re: Small prog question from a newbie: abt variables in a function definition
At Wednesday 29/11/2006 06:48, B Shyam Sundar wrote: I am a newbie as far as python is concerned ... I am trying to write a code for playing bridge in obj oriented manner .. Well ... i have this small problem: class hand: def __init__(self,set_of_cards=[]): self.set_of_cards=set_of_cards card_played_flag =0 def play(played_card): for i in self.set_of_cards: if self.set_of_cards[i] == played_card: self.set_of_cards.remove (played_card) def sort_hand(): for i in self.set_of_cards: for j in self.set_of_cards: if self.set_of_cards[j].faceself.set_of_cards[i].face self.set_of_cards [j],self.set_of_cards[i]=self.set_of_cards[i],self.set_of_cards[j] for i in self.set_of_cards: for j in self.set_of_cards: if self.set_of_cards[j].suitself.set_of_cards[i].suit self.set_of_cards[j],self.set_of_cards[i]=self.set_of_cards[i],self.set_of_cards[j] I have created card as a class with the attributes of suit face so .. card(suit,face) So my question is this --- The compiler doesnt recognise that there is self.set_of_cards[j] can be a card. It gives a syntax error. Also I have not created any instance of the class (Can that be a problem) (The compiler knows very few about your cards... Python is a very dynamic language, a lot of things happens at runtime) Without compiling your example, I can see these syntax errors: 1) In Python indentation matters. sort_hand must have the same indentation as play (and the other methods). 2) Syntax for the if statement - you need a final : if condition: something if condition: do something and do other thing and do another thing So how do i fix this? Also can I specify that the list set_of_cards has only card objects? IF yes how? Short answer: don't bother. (Yes, you *could* inherit from list and restrict the contained items, but it's seldom used). You don't have to sort manually, this should work: set_of_cards.sort(key=lambda card: (card.suit,card.face)) And don't use a mutable initializer in __init__: either use an empty tuple () or use None and check for it in the method body: def __init__(self, set_of_cards=None): if set_of_cards is None: set_of_cards=[] self.set_of_cards = set_of_cards -- Gabriel Genellina Softlab SRL __ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ¡gratis! ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar -- http://mail.python.org/mailman/listinfo/python-list
Re: Asyncore Medusa Example
At Wednesday 29/11/2006 07:23, Graeme Matthew wrote: does anyone know where you can find examples of how to write a native python webserver, I have looked at medusa and asyncore but there are no real examples and the doco is very light The Python standard library already comes with a native HTTP server. And you have menctioned Medusa, and there is also Twisted and... try google to find more examples. Do you want to write *another* one? -- Gabriel Genellina Softlab SRL __ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ¡gratis! ¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar -- http://mail.python.org/mailman/listinfo/python-list
Re: utf - string translation
Dan wrote: On 22 nov, 22:59, John Machin [EMAIL PROTECTED] wrote: processes (Vigenère) So why do you want to strip off accents? The history of communication has several examples of significant difference in meaning caused by minute differences in punctuation or accents including one of which you may have heard: a will that could be read (in part) as either a chacun d'eux million francs or a chacun deux million francs with the remainder to a 3rd party. of course. My purpose is not doing something realistic on a cryptographic view. It's for learning rudiments of programming. In fact, coding characters is a kind of cryptography I mean, sometimes, when friends can't read an email because of the characters used... I wanted to strip off accents because I use the frequences of the charactacters. If I only have 26 char, it's more easy to analyse (the text can be shorter for example) Try this: from_characters = '\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd8\xd9\xda\xdb\xdc\xdd\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xff\xe7\xe8\xe9\xea\xeb' to_characters = 'AAACDNOOYaaaonooyyc' translation_table = string.maketrans (from_characters, to_characters) translated_string = string.translate (original_string, translation_table) Frederic -- http://mail.python.org/mailman/listinfo/python-list
Re: proof of concept python and tkinter gnugo interface
Anton Vredegoor wrote: For the last few days I've been doodling with a script that provides a graphical interface to gnugo by using its GTP protocol. At the moment the script is *very* basic, in fact the only thing it does is to allow one to click on a coordinate and place a move there OR press the space bar in order to let gnugo generate a move. However, I feel that this idea has some potential, it could be made to undo or redo moves or load sgf-games. But most importantly: It could load the list of move suggestions from gnugo, do some computations itself in *Python* on that list and then generate a move. So I thought that it would be best to present this script while it is still small and modifications can be done easily. In the end there's possibly a lot of potential and I think I'm going to need some help from people that are enthousiastic about Python or gnugo. What I want to accomplish with this post is to get to know whether it would be a good idea to make it a sourceforge project (it would be even better if some more experienced sourceforger would do it for me :-) or whether I should just go on doodling on this script by myself, gradually adapting it to fit my personal interests and come back to you in a few years with a more complete script. Is there any need for such a beast for *more* people than just me to work on? Here's the proof of concept, just copy it to some dir and run the Python script: http://home.hccnet.nl/a.vredegoor/gnugo/ It needs Python 2.5 which you can get at: http://www.python.org/ Anton If you talking about a simple gui for gnu go it's been done to death. see any misc. pandanet client and numerous other softwares such as durish or go knot. If your client is going to do something uniquely different from programs like this then you should focus in this aspect of the program and develop other features later. It's also important that it be able to read and write sgf files -- http://mail.python.org/mailman/listinfo/python-list
shtoom or yate client source code
Hello, Can somebody give me (if is that possible) source code of shtoom or yate client ( e.g. yate.exe or shtoom.exe client source code) and, Do you know any python voip module except shtoom and yate,if you know please tell me. I will appreciate any help!! Regards,Vedran -- http://mail.python.org/mailman/listinfo/python-list
Re: Really closing stdout (was: fork and exit needed?)
Mitja Trampus [EMAIL PROTECTED] wrote: Nick Craig-Wood wrote: I'm not sure how you do open stdout to /dev/null in python though! I suspect something like this... import posix posix.close(1) posix.open(/dev/null, posix.O_WRONLY) Yes, you're close enough... The explanations are here: http://www.google.com/search?q=python%20close%20stdout, I like this one in particular: http://www.python.org/infogami-faq/library/why-doesn-t-closing-sys-stdout-stdin-stderr-really-close-it/ If you explicitly want to leave file descriptors 0-2 present (Do you gain anything by not closing them? If you know, do tell...), It is traditional I think... From the unix FAQ, http://www.erlenstar.demon.co.uk/unix/faq.txt :- 6. `close()' fds 0, 1, and 2. This releases the standard in, out, and error we inherited from our parent process. We have no way of knowing where these fds might have been redirected to. Note that many daemons use `sysconf()' to determine the limit `_SC_OPEN_MAX'. `_SC_OPEN_MAX' tells you the maximun open files/process. Then in a loop, the daemon can close all possible file descriptors. You have to decide if you need to do this or not. If you think that there might be file-descriptors open you should close them, since there's a limit on number of concurrent file descriptors. 7. Establish new open descriptors for stdin, stdout and stderr. Even if you don't plan to use them, it is still a good idea to have them open. The precise handling of these is a matter of taste; if you have a logfile, for example, you might wish to open it as stdout or stderr, and open `/dev/null' as stdin; alternatively, you could open `/dev/console' as stderr and/or stdout, and `/dev/null' as stdin, or any other combination that makes sense for your particular daemon. but pointing do /dev/null, you could do: null = os.open(os.devnull,os.O_WRONLY) os.dup2(null,0) os.dup2(null,1) os.dup2(null,2) os.close(null) Untested. Ah, dup2() was on the tip of my mind's tongue ;-) You could write it like this, and then it even works on Windows! import os import sys import time print os.getpid() null = os.open(os.devnull,os.O_RDWR) os.dup2(null, sys.stdin.fileno()) os.dup2(null, sys.stdout.fileno()) os.dup2(null, sys.stderr.fileno()) os.close(null) print You won't see this print sys.stderr, Or this time.sleep(60) -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: shtoom or yate client source code
Croteam wrote: Can somebody give me (if is that possible) source code of shtoom or yate client Take a look at the SourceForge downloads page for Shtoom: http://sourceforge.net/project/showfiles.php?group_id=94774 The project is actually hosted at divmod.com... http://www.divmod.org/trac/wiki/ShtoomProject ...and although the repository doesn't seem to be viewable via the Browse Source link on that page, the stated link to the repository does work with Subversion. Paul -- http://mail.python.org/mailman/listinfo/python-list
Processing Solid Edge objects
I consider using Python to process Solid Edge .par .asm etc objects. Solid Edge provides a pretty rich documentation and tutorials. Still, when trying it out, using PyWin32, I get somewhat frustrated. So, I hope for someone out there to be willing to share experiences. The objective is to automate generation of customer specific machine elements from project spec's. In particular, we wish to be able to use .par files as templates and, by taking a copy and changing attribute values, instantiate components to be used in an assembly. The end result shall be a complete construction structure from which, among many things, customer doc's drawings and Bill Of Materials are to be extracted. //M -- http://mail.python.org/mailman/listinfo/python-list
Re: Wrapping A Shell
Jeremy Moles [EMAIL PROTECTED] wrote: I'm not sure if this is really the right place to ask this question, but since the implementation is in Python, I figured I'd give it a shot. I want to wrap a shell process using popen inside of python program rather than creating a new shell process for each line I process in the app. For example, the code might look like: std = stdin, stdout, stderr = os.popen3(bash) print stdin, ls print stdout.readline() However, it appears my understanding of popen (or perhaps buffered IO) is off somewhere, because this certainly doesn't work anything like I expect it to (it hangs on stdout.readline). Obviously the example above is very contrived, but eventually I'll be using this in an OpenGL terminal widget. Am I approaching this the wrong way? Short answer: use pexpect http://pexpect.sourceforge.net/ Long answer: Firstly modern pythonistas use subprocess instead of os.popen*. Secondly, buffering is going to cause you trouble and possible deadlocks. There are two ways to rid yourself of deadlock. 1) read and write from seperate threads / processes. This is the traditional unix way 2) use non blocking IO Here is a possible way to solve the problems with subprocess (unix only) and non blocking IO. However I suspect you really want to use pexpect for this job... from os import O_NONBLOCK from errno import EAGAIN from subprocess import Popen, PIPE from fcntl import fcntl, F_SETFL, F_GETFL from time import time p = Popen([/bin/bash, -i], shell=False, bufsize=0, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) # Make output streams non blocking (unix only) for fd in (p.stdout.fileno(), p.stderr.fileno()): fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK) def read_output(p, timeout=1.0): Read the output from the subprocess, with timeout end_time = time() + timeout output = while time() end_time: try: output += p.stdout.read(1024) except IOError, e: if e.errno != EAGAIN: raise return output p.stdin.write(ls\n) print read_output(p) p.stdin.write(uname -a\n) print read_output(p) -- Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with imaplib (weird result if mailbox contains a %)
Antoon Pardon wrote: On 2006-11-28, Leo Kislov [EMAIL PROTECTED] wrote: Antoon Pardon wrote: This little program gives IMO a strange result. import imaplib user = cpapen cyr = imaplib.IMAP4(imap.vub.ac.be) cyr.login(cyrus, cOn-A1r) rc, lst = cyr.list('', user/%s/* % user) for el in lst: print %r % (el,) And the result is: '(\\HasNoChildren) / user/cpapen/Out' '(\\HasNoChildren) / user/cpapen/Punten' '(\\HasNoChildren) / user/cpapen/Spam' '(\\HasNoChildren) / user/cpapen/agoog to be' '(\\HasNoChildren) / user/cpapen/artistiek - kunst' '(\\HasNoChildren) / user/cpapen/copains et copinnes =x=' '(\\HasNoChildren) / user/cpapen/cp - writing' '(\\HasNoChildren) / user/cpapen/examen' '(\\HasNoChildren) / user/cpapen/important info (pass)' '(\\HasNoChildren) / user/cpapen/lesmateriaal' '(\\HasNoChildren) / user/cpapen/love - flesh for fantasy' '(\\HasNoChildren) / user/cpapen/media' '(\\HasNoChildren) / user/cpapen/music - beats' ('(\\HasNoChildren) / {25}', 'user/cpapen/newsletters %') '' '(\\HasNoChildren) / user/cpapen/organisatie - structuur' '(\\HasNoChildren) / user/cpapen/sociale wetenschappen' '(\\HasNoChildren) / user/cpapen/the closest ones to me [x]' '(\\HasNoChildren) / user/cpapen/vubrations' '(\\HasNoChildren) / user/cpapen/wm2addressbook' '(\\HasNoChildren) / user/cpapen/wm2prefs' '(\\HasNoChildren) / user/cpapen/wm2signature' What I have a problem with is the 14th and 15th line. All other entries are strings but the 14th is a tuple. and the 15th is an empty string. As far as I can tell every time a % is in the mailbox name I get this kind of result. I'm using python 2.3.3 and the imap sytem is Cyrus. Can someone explain what is going one? Is this a bug? Empty string seems to be a bug. But tuple is by design, read the docs and imap rfc. The protocol is convoluted in the first place, and so is python interface. Are there more docs than at http://www.python.org/doc/. I don't find those very helpfull in explaining this. I also took a look at rfc 2060 and to be honest I don't find anything there to explain this difference. I only took a closer look at section 7.2.2. So maybe I should look somewehere else but after reading section 7.2.2. I don't understand why the list method returned a tuple for this mailbox instead of the following string: '(\\HasNoChildren) / user/cpapen/newsletters %' This is described in section 4.3. imaplib is too close to the protocol. It should interpret response for each command separately. For example list method could return list of tuples like: (\\HasNoChildren, /, user/cpapen/newsletters %) Without this abstraction level in imaplib you have to build it yourself. If it is, is it fixed in later versions? Why don't you try to pull imaplib.py from later versions? I don't think it changed that much so it should be compatible with python 2.3 I could take my hands on a 2.4 version and the result was the same. I was talking only about empty string response. Is it still there? Anyway, this issue requires investigation. That could also be a bug in the server. -- Leo -- http://mail.python.org/mailman/listinfo/python-list
Re: Processing Solid Edge objects
It would help if you could give an exemple of .par and .asm file. Is it human readable, XML ... ? Is there any other import/export file format provided ? Maria R a écrit : I consider using Python to process Solid Edge .par .asm etc objects. Solid Edge provides a pretty rich documentation and tutorials. Still, when trying it out, using PyWin32, I get somewhat frustrated. So, I hope for someone out there to be willing to share experiences. The objective is to automate generation of customer specific machine elements from project spec's. In particular, we wish to be able to use .par files as templates and, by taking a copy and changing attribute values, instantiate components to be used in an assembly. The end result shall be a complete construction structure from which, among many things, customer doc's drawings and Bill Of Materials are to be extracted. //M -- http://mail.python.org/mailman/listinfo/python-list
Re: Problem with imaplib (weird result if mailbox contains a %)
On 2006-11-29, Leo Kislov [EMAIL PROTECTED] wrote: Antoon Pardon wrote: On 2006-11-28, Leo Kislov [EMAIL PROTECTED] wrote: Are there more docs than at http://www.python.org/doc/. I don't find those very helpfull in explaining this. I also took a look at rfc 2060 and to be honest I don't find anything there to explain this difference. I only took a closer look at section 7.2.2. So maybe I should look somewehere else but after reading section 7.2.2. I don't understand why the list method returned a tuple for this mailbox instead of the following string: '(\\HasNoChildren) / user/cpapen/newsletters %' This is described in section 4.3. imaplib is too close to the protocol. It should interpret response for each command separately. For example list method could return list of tuples like: (\\HasNoChildren, /, user/cpapen/newsletters %) Without this abstraction level in imaplib you have to build it yourself. Ah yes, I'm beginning to understand now, what is going on. I also did a imap session by hand using telnet. That helped. If it is, is it fixed in later versions? Why don't you try to pull imaplib.py from later versions? I don't think it changed that much so it should be compatible with python 2.3 I could take my hands on a 2.4 version and the result was the same. I was talking only about empty string response. Is it still there? Anyway, this issue requires investigation. That could also be a bug in the server. The empty line is still there using 2.4. This is part of the session I did by hand. It doesn't seem to be a server problem. $ telnet machine.domain imap Trying xxx.xxx.xxx.xxx... Connected to machine.domain Escape character is '^]'. * OK maxi Cyrus IMAP4 v2.2.13 server ready 0001 LOGIN ... 0001 OK User logged in 0002 LIST user/cpapen/* * LIST (\HasNoChildren) / user/cpapen/Out ... * LIST (\HasNoChildren) / user/cpapen/music - beats * LIST (\HasNoChildren) / {25} user/cpapen/newsletters % * LIST (\HasNoChildren) / user/cpapen/organisatie - structuur * LIST (\HasNoChildren) / user/cpapen/sociale wetenschappen ... Many thanks for your contribution. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list
Re: screen output problem
I'm not sure if there is a definite solution to this problem. I've noticed that one of the applications, which I use on a daily basis (apt from Debian) does address the progress bar issue in another way. When apt tries to download multiple files, it displays the progress of all the downloads on a single line. Probably the apt developers also might have run into the same issue and hence settled down with this workaround. Thanks, Ritesh Dennis Lee Bieber wrote: On Tue, 28 Nov 2006 15:15:28 +0530, Ritesh Raj Sarraf [EMAIL PROTECTED] declaimed the following in comp.lang.python: If there's a way to print multiple lines of text withouth the newline (\n) character, we can then use carriage return (\r) and implement a proper progressbar with a bar for each separate progress action. If you were running on an Amiga, or via a serial port connection to an old VT-100 terminal, it would be child's play... Since both understood the same terminal control codes for moving the cursor around a text display. The old MS-DOS ANSI console driver may have understood that set. But M$, in its great and all-powerful wisdom, seems to feel that the only need for a command line interface is for batch configuration scripts that run with no human interaction, and hence with no need for status. One is expected to code a GUI instead if such things as progress-bars are needed. A google for windows console cursor control brings up (a bit of a surprise since I my search terms didn't mention Python): http://newcenturycomputers.net/projects/wconio.html Of course, this isn't portable to LINUX or other operating systems... Also, looking at win32api, I find a SetCursorPos() (and matching get...). -- WulfraedDennis Lee Bieber KD6MOG [EMAIL PROTECTED] [EMAIL PROTECTED] HTTP://wlfraed.home.netcom.com/ (Bestiaria Support Staff: [EMAIL PROTECTED]) HTTP://www.bestiaria.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Processing Solid Edge objects
olive skrev: It would help if you could give an exemple of .par and .asm file. Is it human readable, XML ... ? Is there any other import/export file format provided ? The .par files and friends are in binary format so the method I prefer is using the provided COM interfaces and access the various objects that way. Therefor I seek advice from those who have tried this so I may decide whether I shall pursue the Python trail or go for some other language like VB or C# where there are code samples. -- http://mail.python.org/mailman/listinfo/python-list
Re: Error handling. Python embedded into a C++ app.
[EMAIL PROTECTED] [EMAIL PROTECTED] wrote: You would use try: and then on the next line except: Thanks for the idea, but it did not help. I can not wrap every pythion line in python, so I wrote the following code on the C++ side: -- snip - try { int ret = PyRun_SimpleString ( p ) ; if(ret==-1) { ::MessageBox(0, Error in Python call!, , 0); } else { assert(ret == 0); } } catch( ...) { ::MessageBox(0, exception, , 0 ); } -- snip - I call this where p is an execute of a *.py file containing an error. I get the Error in Python call!, but not the exception. Any help, including links to information, welcome. TIA, Wolfram Kuss. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: CherryPy 3.0 RC1
Christian Wyglendowski [EMAIL PROTECTED] writes: I'm happy to announce the first release candidate for CherryPy 3.0. Ben Finney wrote: Congratulations, I'm glad to see an announcement for CherryPy. Please, in future, don't send HTML message bodies to public forums; plain text is far better for such a wide audience. My apologies. I wrongly assumed that anyone using an email client that only supported plain text would simply use the plain text part of the email. Thanks for bringing this to my attention. Christian http://www.dowski.com -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: CherryPy 3.0 RC1
On 2006-11-29 08:37:46 -0500, Christian [EMAIL PROTECTED] said: Christian Wyglendowski [EMAIL PROTECTED] writes: I'm happy to announce the first release candidate for CherryPy 3.0. Ben Finney wrote: Congratulations, I'm glad to see an announcement for CherryPy. Please, in future, don't send HTML message bodies to public forums; plain text is far better for such a wide audience. My apologies. I wrongly assumed that anyone using an email client that only supported plain text would simply use the plain text part of the email. Thanks for bringing this to my attention. Christian http://www.dowski.com Some people are reading this on comp.lang.python. Best, James -- http://mail.python.org/mailman/listinfo/python-list
Re: pyxpcom
Trent Mick wrote: My need is as follows: I have developed an activex component to access a smart card on the client side / do some web site logon. Are xpcom / pyxpcom advanced/stable enough for such an implementation under Linux / Windows ? You mean to provide the equivalent functionality for Firefox that your activex component does for IE? Yes, xpcom and pyxpcom are quite stable, however putting together a Firefox extension that gets PyXPCOM itself up and running in a client's Firefox install will be quite challenging. Trent Exactly ... are you saying I need to distribute Firefox compiled differently in order to achieve that ? This is less a python issue clearly if that is the case: would I have the same issues to resolve if I were to write the module in C++ ? Thanks, hg -- http://mail.python.org/mailman/listinfo/python-list
odict the Ordered Diction 0.2.2
After a break of almost a year there has been an update to `odict the Ordered Dictionary http://www.voidspace.org.uk/python/odict.html`_. The latest version is 0.2.2, with changes implemented by Nicola Larosa. Despite over 700 downloads since May (plus 1300 as part of `pythonutils http://www.voidspace.org.uk/python/pythonutils.html`_) there have been no bug reports, only improvements [#]_. {sm;:-)} * `Quick Download http://www.voidspace.org.uk/cgi-bin/voidspace/downman.py?file=odict.py`_ What is odict? == **odict** is a pure Python implementation of an ordered dictionary. It keeps keys in insertion order and allows you to change the order. Methods (including iteration) that would return members in an arbitrary order are now ordered. There is also the `SequenceOrderedDict http://www.voidspace.org.uk/python/odict.html#sequenceordereddict`_ that behaves like a sequence as well as a dictionary. It allows slicing and the keys, values and items methods are special sequence objects (which are also callable and so behave as methods too). What's New ? == Code --- Removed the TODO and CHANGELOG sections in the tail docstring (they are in the docs anyway). Disabled warnings during tests. Explicitly disabled tests execution on Python v.2.2 . In addition to the slicing tests, other ones are failing. Removed code duplication between the ``__init__`` and the ``update`` methods. Misc. cleanup. Also, based on code from `Tim Wegener`_: - added the ``rename`` method; - removed a ``has_key`` usage in the ``__setitem__`` method. Documentation -- Moved the ISSUES chapter from code's tail docstring to here. Moved up the `Creating an Ordered Dictionary http://www.voidspace.org.uk/python/odict.html#creating-an-ordered-dictionary`_ chapter. Added prompts to the code examples and removed the superfluous print statements (sometimes they were there, sometimes they were not). Misc. cleanup. .. [#] So either no-one is using it, or it's really good... -- http://mail.python.org/mailman/listinfo/python-list
Stani's Python Editor is looking for a new webhost
SPE was hosted for a long while by Zettai. I'd like to thank them again for their wonderful service. Unfortunately they will go out of business. So SPE is looking for a new webhost. These are the requirements: - python framework (Zope/Plone, django, turbogears, ...) - I have the freedom to use this website also for other projects besides SPE (such as sdxf (open source dxf library for python), my own portfolio, ... - I am allowed to place ads on the site (eg Google Adsense) These are some optional features which would be nice: - root access - debian or ubuntu based - domain registration for stani.be In return a small banner of the hosting (or sponsering) will be placed on the SPE site. You can reach me by email: spe.stani.be at gmail. The SPE website gets around 1500 visitors a day. If there are some zope/plone, django, turbogears, ... enthousiasts or companies want to help building the site, please contact me as well. Every offer will be appreciated, but of course I can only choose one. In order to continue the development of SPE, it needs a hosting provider. Thanks for any suggestions, Stani -- http://mail.python.org/mailman/listinfo/python-list
trouble writing results to files
I have two semi related questions... First, I am trying to output a list of strings to a csv file using the csv module. The output file separates each letter of the string with a comma and then puts each string on a separate line. So the code is: import csv output = csv.writer(open('/Python25/working/output.csv', 'a')) a = [apple, cranberry, tart] for elem in range(len(a)): output.writerow(a[elem]) ... and it would write to the file: a,p,p,l,e c,r,a,n,b,e,r,r,y t,a,r,t How do I get it to write apple, cranberry, tart ? Second, there is a significant delay (5-10 minutes) between when the program finishes running and when the text actually appears in the file. Any ideas for why this happens? It is the same for writing with the csv module or the standard way. thanks! Lisa -- http://mail.python.org/mailman/listinfo/python-list
Calling functions with dynamic arguments
I have a dictionary like: {a:1, b:2} and I want to call a function: def func1(a=3,b=4): print a,b so that I get a=1,b=2, how can I go about that? Thanks, Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling functions with dynamic arguments
SeanDavis12 wrote: I have a dictionary like: {a:1, b:2} and I want to call a function: def func1(a=3,b=4): print a,b so that I get a=1,b=2, how can I go about that? func1(**yourdict) -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting recursion loops
robert wrote: My code does recursion loops through a couple of functions. Due to problematic I/O input this leads sometimes to endless recursions and after expensive I/O to the Python recursion exception. What would be a good method to detect recursion loops and stop it by user-Exception (after N passes or some complex criteria) without passing a recursion counter parameter through all the funcs? What about `sys.setrecursionlimit`? http://docs.python.org/lib/module-sys.html -- HTH, Rob -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble writing results to files
[EMAIL PROTECTED] wrote: import csv output = csv.writer(open('/Python25/working/output.csv', 'a')) a = [apple, cranberry, tart] for elem in range(len(a)): output.writerow(a[elem]) output.writerow expects a sequence as an argument. You are passing a string, which is a sequence of characters. By the way, what output are you expecting to get? Do you want a file with only one line (apple, cranberry, tart), or each fruit in a different line? BTW, iterating over range(len(a)) is an anti-pattern in Python. You should do it like this: for item in a: output.writerow([item]) Second, there is a significant delay (5-10 minutes) between when the program finishes running and when the text actually appears in the file. Try closing the file explicitly. Cheers, -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: Calling functions with dynamic arguments
Roberto Bonvallet wrote: SeanDavis12 wrote: I have a dictionary like: {a:1, b:2} and I want to call a function: def func1(a=3,b=4): print a,b so that I get a=1,b=2, how can I go about that? func1(**yourdict) Thanks, Roberto. Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble writing results to files
On 2006-11-29, Roberto Bonvallet [EMAIL PROTECTED] wrote: BTW, iterating over range(len(a)) is an anti-pattern in Python. Unless you're modifying elements of a, surely? -- Neil Cerutti You can't give him that cutback lane. He's so fast, and he sees it so well. He can also run away from you if he gets a little bit of crack. --Dick Lebeau -- http://mail.python.org/mailman/listinfo/python-list
How to detect what type a variable is?
Hi, I want to know what type is a variable. For example, I get the contents of an xml but some content is a list or a string, and I need to know what type it is. Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble writing results to files
Neil Cerutti wrote: On 2006-11-29, Roberto Bonvallet [EMAIL PROTECTED] wrote: BTW, iterating over range(len(a)) is an anti-pattern in Python. Unless you're modifying elements of a, surely? enumerate is your friend :) for n, item in enumerate(a): if f(item): a[n] = whatever -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
On 2006-11-29, Leandro Ardissone [EMAIL PROTECTED] wrote: I want to know what type is a variable. For example, I get the contents of an xml but some content is a list or a string, and I need to know what type it is. x = 'asdf' type(x) type 'str' i = 0 type(i) type 'int' -- Grant Edwards grante Yow! I Know A Joke!! at visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
On 2006-11-29, Grant Edwards [EMAIL PROTECTED] wrote: On 2006-11-29, Leandro Ardissone [EMAIL PROTECTED] wrote: I want to know what type is a variable. For example, I get the contents of an xml but some content is a list or a string, and I need to know what type it is. x = 'asdf' type(x) type 'str' i = 0 type(i) type 'int' That makes me wonder how he manages to store Python objects in xml. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
Leandro Ardissone wrote: Hi, I want to know what type is a variable. For example, I get the contents of an xml but some content is a list or a string, and I need to know what type it is. type(variable) Sean -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble writing results to files
On 2006-11-29, Roberto Bonvallet [EMAIL PROTECTED] wrote: Neil Cerutti wrote: On 2006-11-29, Roberto Bonvallet [EMAIL PROTECTED] wrote: BTW, iterating over range(len(a)) is an anti-pattern in Python. Unless you're modifying elements of a, surely? enumerate is your friend :) for n, item in enumerate(a): if f(item): a[n] = whatever I was going to bring it up but I had a brainfart about the order of (n, item) in the tuple and was too lazy to look it up. ;-) -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting recursion loops
robert wrote: My code does recursion loops through a couple of functions. Due to problematic I/O input this leads sometimes to endless recursions and after expensive I/O to the Python recursion exception. What would be a good method to detect recursion loops and stop it by user-Exception (after N passes or some complex criteria) without passing a recursion counter parameter through all the funcs? 1. You could catch RuntimeError at the top, check whether it's recursion depth exception, and raise a user exception if it is. 2. Consider whether you're unwittingly trying to cover up a bug. ISTM no matter how problematic the input is, you should at least be able to make progress on it. Are you getting this error because, say, you're not incrementing a counter somewhere, and thus recalling a function with the same arguments again? 3. Also consider whether you could rewrite the code to be non-recursive. Usually when I process input recursively, the input is allowed to be arbitrarily deeply nested. (In that case I think it would be a mistake to arbitrarily limit depth.) But it sounds to me like your input might be inherently non-nestable. If that's the case, it might be possible to get rid of the recursion altogether, or at least to put in error checking that detects when input is at an invalid depth. 4. If those concerns don't apply, and you do need to detect recursion, I'd suggest using a global dictionary to track function calls. If you have a function parse_something that you want to track, you could define a dict like this: _call_count = { parse_something: 0 } And change parse_something to adjust its own counter: def parse_something(): _call_count[parse_something] += 1 check_invalid_recursion() _call_count[parse_something] -= 1 (You could define a decorator to do this more easily; that's left as an excercise.) The check_invalid_recursion() function would inspect _call_count and raise an exception based on any criteria you want. 5. In CPython, you could just inpect the stack frame and look for duplicated function calls. See the documentation for sys._getframe. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Asyncore Medusa Example
Graeme Matthew wrote: does anyone know where you can find examples of how to write a native python webserver, I have looked at medusa and asyncore but there are no real examples and the doco is very light medusa *is* a web server based on asyncore, so you should be able to use it more or less as is. for an overview of asyncore, see: http://effbot.org/librarybook/asyncore.htm (basics, http client example) http://effbot.org/librarybook/asynchat.htm (http server example) /F -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble writing results to files
Neil Cerutti wrote: BTW, iterating over range(len(a)) is an anti-pattern in Python. Unless you're modifying elements of a, surely? and needs to run on a Python version that doesn't support enumerate. /F -- http://mail.python.org/mailman/listinfo/python-list
Overloading if object unary operator
Good morning, If I have a class class A: __init__(id) self.id = id is there any way to overload the 'if' unary usage to detect if a variable has a value? For example, in the code: a = A(56) if a: print Hoo hah! how can I insure that the if will come back true and fire off the print if and only if self.id is defined? I want to do this in an overloaded, generic way, if possible; I know that I could test for a.id. Thanks so much! -Jason Ledbetter -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble writing results to files
Roberto Bonvallet wrote: [EMAIL PROTECTED] wrote: import csv output = csv.writer(open('/Python25/working/output.csv', 'a')) a = [apple, cranberry, tart] for elem in range(len(a)): output.writerow(a[elem]) output.writerow expects a sequence as an argument. You are passing a string, which is a sequence of characters. By the way, what output are you expecting to get? Do you want a file with only one line (apple, cranberry, tart), or each fruit in a different line? I want it to print everything on one line and then create a new line where it will print some more stuff. In my real program I am iterating and it will eventually print the list a couple hundred times. But it would be useful to understand how to tell it to do either. BTW, iterating over range(len(a)) is an anti-pattern in Python. You should do it like this: for item in a: output.writerow([item]) I can try that. Is using range(len(a)) a bad solution in the sense that its likely to create an unexpected error? Or because there is a more efficient way to accomplish the same thing? thanks! Lisa -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading GDSII layouts
Le mardi 28 novembre 2006 17:56, Paddy a écrit : The link you gave states this near the top: IPKISS is a python-based library for the generation of GDSII layouts, including hierarchy. It has grown out of the GDS_KEY library, but it is more flexible and object oriented. Contrary to GDS_KEY, **it can read and edit existing GDSII files**. And at the bottom of the page: * Import of existing GDSII files into a layout (import.py) It looks to be a reader?! - Paddy. Yes, you are right, but I am actually looking for a library that would display only cell references, and not load the entire design (what will be too time consuning with Python). And this doesn't look to be present in IPKiss. Vincent -- http://mail.python.org/mailman/listinfo/python-list
Re: Reading GDSII layouts
Le mardi 28 novembre 2006 18:46, Jacob Rael a écrit : Funny, I started writing one this past weekend as a learning exercise (handling large files and start to use classes). If ipkiss does not work out, let me know specifically what you need and maybe my hack will work. jr Well, if you know how to extract cell names and references from a GDSII layout, that would be usefull. Perhaps can you send me your code if you don't mind and I will try to do something from it ? Vincent -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloading if object unary operator
Sarcastic Zombie wrote: For example, in the code: a = A(56) if a: print Hoo hah! how can I insure that the if will come back true and fire off the print if and only if self.id is defined? I want to do this in an overloaded, generic way, if possible; I know that I could test for a.id. Define a method called __nonzero__ that returns True or False. -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
great, thanks And how I can compare this type 'str' output ? I want to decide what to do if the var is an string and what to do if not.. Tried with: if type(artistList) == type 'list': and if type(artistList) == list: but nothing.. On Nov 29, 12:41 pm, Grant Edwards [EMAIL PROTECTED] wrote: On 2006-11-29, Leandro Ardissone [EMAIL PROTECTED] wrote: I want to know what type is a variable. For example, I get the contents of an xml but some content is a list or a string, and I need to know what type it is. x = 'asdf' type(x) type 'str' i = 0 type(i) type 'int'-- Grant Edwards grante Yow! I Know A Joke!! at visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
Thanks, I don't store Python objects in xml, but I get an object from a library that parses xml and converts it to objects. On Nov 29, 12:43 pm, Neil Cerutti [EMAIL PROTECTED] wrote: On 2006-11-29, Grant Edwards [EMAIL PROTECTED] wrote: On 2006-11-29, Leandro Ardissone [EMAIL PROTECTED] wrote: I want to know what type is a variable. For example, I get the contents of an xml but some content is a list or a string, and I need to know what type it is. x = 'asdf' type(x) type 'str' i = 0 type(i) type 'int'That makes me wonder how he manages to store Python objects in xml. -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloading if object unary operator
Sarcastic Zombie wrote: is there any way to overload the 'if' unary usage to detect if a variable has a value? Define a __nonzero__() or __len__() method. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
Leandro Ardissone wrote: And how I can compare this type 'str' output ? I want to decide what to do if the var is an string and what to do if not.. Tried with: if type(artistList) == type 'list': and if type(artistList) == list: but nothing.. type() doesn't return a string, it returns a type object. You should try this: if isinstance(artistList, list): ... Cheers, -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloading if object unary operator
On Nov 29, 11:26 am, Peter Otten [EMAIL PROTECTED] wrote: Sarcastic Zombie wrote: is there any way to overload the 'if' unary usage to detect if a variable has a value?Define a __nonzero__() or __len__() method. Peter Thanks to both of you, it worked perfectly. I must have missed it in the documentation somehow. -Jason Ledbetter -- http://mail.python.org/mailman/listinfo/python-list
Re: trouble writing results to files
[EMAIL PROTECTED] wrote: I can try that. Is using range(len(a)) a bad solution in the sense that its likely to create an unexpected error? Or because there is a more efficient way to accomplish the same thing? for-in uses an internal index counter to fetch items from the sequence, so for item in seq: function(item) is simply a shorter and more efficient way to write for item in range(len(seq)): function(seq[item]) also see this article: http://online.effbot.org/2006_11_01_archive.htm#for /F -- http://mail.python.org/mailman/listinfo/python-list
Using Python
Hi Guys, I am new to this language and i need some help... I am trying to create a script that will go into a log file and bring me back the xml from an order... For example: go into Log1.xml and extract order number 2 from top to bottom and extract it into a txt file... Does anyone know how i can create this type of script or has like a sample that i can use.. I am having a hard time starting the script.. hope someone can help Thanks agian -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
great, that is just what I need! Thank you all! -- Leandro Ardissone On Nov 29, 1:29 pm, Roberto Bonvallet [EMAIL PROTECTED] wrote: Leandro Ardissone wrote: And how I can compare this type 'str' output ? I want to decide what to do if the var is an string and what to do if not.. Tried with: if type(artistList) == type 'list': and if type(artistList) == list: but nothing..type() doesn't return a string, it returns a type object. You should try this: if isinstance(artistList, list): ... Cheers, -- Roberto Bonvallet -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
On 29 Nov 2006 08:25:35 -0800, Leandro Ardissone [EMAIL PROTECTED] wrote: great, thanks And how I can compare this type 'str' output ? I want to decide what to do if the var is an string and what to do if not.. Tried with: if type(artistList) == type 'list': and if type(artistList) == list: but nothing.. Try it this way... artistList = [] isinstance(artistList, list) True if isinstance(artistList, list): print I'm a list. I'm a list. Daniel Klein -- http://mail.python.org/mailman/listinfo/python-list
Re: Overloading if object unary operator
Sarcastic Zombie wrote: If I have a class class A: __init__(id) self.id = id is there any way to overload the 'if' unary usage to detect if a variable has a value? http://effbot.org/pyref/__nonzero__ /F -- http://mail.python.org/mailman/listinfo/python-list
Re: why would anyone use python when java is there?
gregarican wrote: gavino wrote: wtf You have to be trolling I would think. Yeah, gavino has been trolling comp.lang.lisp for quite some time. For the life of me I can't understand why he would troll comp.lang.python when comp.lang.lisp is there. -Adam -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
Leandro Ardissone wrote: Hi, I want to know what type is a variable. For example, I get the contents of an xml but some content is a list or a string, and I need to know what type it is. You should try to treat it as a list, catch the exceptions raise when it is a string (problably ValueError, TypeError ou Attribute error, depends on what are you doing), and then treat it as a string. This is the BAFP (better ask for forgiveness than permission) style, and is more accepted in duck-typing languages like Python then LBYL (look before you leep) style. -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python
beemer328i2004 wrote: Hi Guys, I am new to this language and i need some help... I am trying to create a script that will go into a log file and bring me back the xml from an order... For example: go into Log1.xml and extract order number 2 from top to bottom and extract it into a txt file... Does anyone know how i can create this type of script or has like a sample that i can use.. I am having a hard time starting the script.. hope someone can help Thanks agian You might want to start here: http://diveintopython.org/ hg -- http://mail.python.org/mailman/listinfo/python-list
Re: why would anyone use python when java is there?
+1 Éric Daigneault wrote: wtf a reasonable question... But before I run circle yelling the trolls are here, the trolls are here I got one for you... why would anyone use java when python is there?? ;-) .^_^. Eric :D, -- http://mail.python.org/mailman/listinfo/python-list
Re: pyxpcom
hg wrote: Trent Mick wrote: My need is as follows: I have developed an activex component to access a smart card on the client side / do some web site logon. Are xpcom / pyxpcom advanced/stable enough for such an implementation under Linux / Windows ? You mean to provide the equivalent functionality for Firefox that your activex component does for IE? Yes, xpcom and pyxpcom are quite stable, however putting together a Firefox extension that gets PyXPCOM itself up and running in a client's Firefox install will be quite challenging. Trent Exactly ... are you saying I need to distribute Firefox compiled differently in order to achieve that ? No. But you'll have to get comfortable building your own Firefox and then building the PyXPCOM extension and then packaging the built PyXPCOM bits that a normal Firefox install does not have already into a Firefox extension. This would also mean packaging up parts of a Python build and possible needing to have a custom Python build to (1) get shared library loading to work correct and (2) ensure there isn't crosstalk between the python that PyXPCOM uses and possibly other Python installations on the target machine. This is less a python issue clearly if that is the case: would I have the same issues to resolve if I were to write the module in C++ ? A little, yes: I believe you'd need a Firefox build in a development tree to build a vanilla C++ XPCOM component. However, I am not sure of that. Mostly, no: You wouldn't need to worry about all the PyXPCOM/Python build/install issues. Trent -- Trent Mick [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
Leandro Ardissone wrote: great, thanks And how I can compare this type 'str' output ? I want to decide what to do if the var is an string and what to do if not.. Tried with: if type(artistList) == type 'list': and if type(artistList) == list: but nothing.. You shouldn't enclose list inside quotes. This is the correct way: if type(artistList) == list: do something... or as someone suggested: if isinstance(l, list): do something... hope this helps. Luis -- http://mail.python.org/mailman/listinfo/python-list
Re: How to refer to Python?
On Tue, 28 Nov 2006 16:51:10 -0500, Fredrik Lundh [EMAIL PROTECTED] wrote: http://effbot.org/pyfaq/are-there-any-published-articles-about-python-that-i-can-reference.htm Maybe: URI:http://www.amazon.com/Introduction-Python-Guido-Van-Rossum/dp/0954161769/sr=8-1/qid=1164818994/ref=sr_1_1/102-2818366-5466542?ie=UTF8s=books Alan Isaac -- http://mail.python.org/mailman/listinfo/python-list
Re: Processing Solid Edge objects
I've done a similar thing with Python and Catia in the past. I used late binding to the Catia objects and I didn't have any real issues. Things to remember: Remove all of the Set statements No need to : set obj = XYZ just obj =XYZ Include the brackets with all Sub calls. VB is sloppy and lets you call subroutines without the brackets, but you have to specify them in Python. It can be a bit tricky passing arrays by reference from Python to a VB subroutine. The advice I found suggested creating a small VB wrapper which creates the array and passes it back to Python. You then call this wrapper from Python. Andy -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
On 2006-11-29, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote: Leandro Ardissone wrote: Hi, I want to know what type is a variable. For example, I get the contents of an xml but some content is a list or a string, and I need to know what type it is. You should try to treat it as a list, catch the exceptions raise when it is a string (problably ValueError, TypeError ou Attribute error, depends on what are you doing), As you said, it depends on what he's doing. The problem is that strings act a lot like lists, and if he's using the subset of list characteristics that are implimented by strings, there won't _be_ an exception -- just wrong results. In the past, I've almost alwasy had to look before I leap when dealing with both strings and lists. -- Grant Edwards grante Yow! How's it going in at those MODULAR LOVE UNITS?? visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
I want to know what type is a variable. You should try to treat it as a list, catch the exceptions raise when it is a string (problably ValueError, TypeError ou Attribute error, depends on what are you doing), and then treat it as a string. This is the BAFP (better ask for forgiveness than permission) style One might prefer to check for string-ness, as strings can duck-type somewhat like lists: my_list = ['my', 'brain', 'hurts'] my_string = 'Are you the brain specialist?' for test in [my_list, my_string]: try: for thing in test: process_list_item(thing) except Exception: #whatever flavor you want process_string(thing) # not called because #strings are iterable This gives the potentially-surprising result of iterating over my_string and calling process_list_item() with each character in the string, rather than raising some exception and calling process_string(). Python does the right thing, but it can be confusing when the duck-typing syntax is identical for the two, despite a desire to treat them differently...perhaps a tree-like list of lists and strings such as HTML/XML structure. -tkc -- http://mail.python.org/mailman/listinfo/python-list
pickle and infinity
Hello, I´ve got this problem with pickle, it seems it doesn´t handle correctly infinite values (nor does Python return overflow/underflow error). What could I do about it? Example code: x = 1e310 #actually it would be a result of calculations type(x) type 'float' x 1.#INF import pickle pickle.loads(pickle.dumps(x)) [...] ValueError: invalid literal for float(): 1.#INF -- http://mail.python.org/mailman/listinfo/python-list
Re: pickle and infinity
To make things more interesting -- Solaris version: x = 1e310 x Infinity import pickle pickle.dumps(x) 'FInfinity\n.' pickle.loads(_) Infinity pickle.dumps(x,1) [...] SystemError: frexp() result out of range -- http://mail.python.org/mailman/listinfo/python-list
Re: pickle and infinity
On 2006-11-29, Bart Ogryczak [EMAIL PROTECTED] wrote: I´ve got this problem with pickle, it seems it doesn´t handle correctly infinite values (nor does Python return overflow/underflow error). What could I do about it? Here's what I did. I'm sure it'll fall down on some systems, but it works on Linux and Windows. __ # unpickle can't handle nan/inf/ind floats, so we need to # handle that ourselves def myload_float(self): s = self.readline()[:-1] try: f = float(s) except ValueError: s = s.upper() if s in [1.#INF, INF]: f = 1e300*1e300 elif s in [-1.#INF, -INF]: f = -1e300*1e300 elif s in [NAN,1.#QNAN,-1.#QNAN,QNAN,1.#IND,IND,-1.#IND]: f = (1e300*1e300)/(1e300*1e300) else: raise ValueError, Don't know what to do with +`s` self.append(f) # unpickle routine that overrides the float load method def unpickle(f): unpickler = pickle.Unpickler(f) unpickler.dispatch[pickle.FLOAT] = myload_float return unpickler.load() __ -- Grant Edwards grante Yow! I represent a at sardine!! visi.com -- http://mail.python.org/mailman/listinfo/python-list
Re: How to refer to Python?
Sebastian Bassi wrote: I am writing a paper where I refer to Python. Is there a paper that I can refer the reader to? Or just use the Python web page as a reference? I´d refer to The Python Language Reference Manual, Guido Van Rossum, Fred L., Jr. Drake Network Theory Ltd (September 2003), ISBN: 0954161785 -- http://mail.python.org/mailman/listinfo/python-list
Re: Using Python
beemer328i2004 wrote: Hi Guys, I am new to this language and i need some help... I am trying to create a script that will go into a log file and bring me back the xml from an order... For example: go into Log1.xml and extract order number 2 from top to bottom and extract it into a txt file... Does anyone know how i can create this type of script or has like a sample that i can use.. I am having a hard time starting the script.. hope someone can help Thanks agian You should also review this module for parsing your XML: http://effbot.org/zone/element-index.htm elementree is now part of the standard library. Note: It would also help if you would post contents of log1.xml so others could see what you are working with. You should also post whatever python code you have tried so far. -Larry -- http://mail.python.org/mailman/listinfo/python-list
Re: How to detect what type a variable is?
One might prefer to check for string-ness, as strings can duck-type somewhat like lists: my_list = ['my', 'brain', 'hurts'] my_string = 'Are you the brain specialist?' for test in [my_list, my_string]: try: for thing in test: process_list_item(thing) except Exception: #whatever flavor you want The exception should be the one that process_list_item raises when it receives a string instead of a list. if you want to treat strings and list in different ways, maybe it means that you are doing different operations on then, like appendind things to the list or whatever. If not, than you maybe want to test the types. process_string(thing) # not called because #strings are iterable What if you invert your code? for test in [my_string, my_list]: try: process_string_item(thing) #suppose process_string_item does some string operation on a list and gets this # exception - because if not, I see no meanning in distinguishing then except ValueError: for thing in test: process_list_item(thing) But maybe you have a reason to do things to a string that could be done to a list without raising an exception, but you dont want to do this to *that* list. My sugestion was to think if there is another way, and maybe you are right. -- EduardoOPadoan (eopadoan-altavix::com) Bookmarks: http://del.icio.us/edcrypt Blog: http://edcrypt.blogspot.com Jabber: edcrypt at jabber dot org ICQ: 161480283 GTalk: eduardo dot padoan at gmail dot com MSN: eopadoan at altavix dot com -- http://mail.python.org/mailman/listinfo/python-list
libboost, python, and dijkstra shortest path
Hi everyone, I need to implement a very quick (performance-wise) Dijkstra shortest path in python, and found that libboost already has such thing. Problem is: I cannot find the installation package for my Python 2.4 under windows. Can someone please provide me instructions for installing libboost for python? In alternative, if someone can point out to a fast Dijkstra shortest path in python (the network is over 1 million vertexes), I would appreciate. Thanks in advance, Hugo Ferreira -- http://mail.python.org/mailman/listinfo/python-list
Surprise with special floating point values
Hi all, While trying to use simplejson under Python 2.4.3 I have been investigating the handling of special floating point values and found that both Python 2.4 and 2.5 return False when comparing a NaN with itself. Although surprising, I imagine it could also be correct since NaN is not a number. But is it correct? Notice the result of comparing c with itself in the following Python 2.5 session (it works the same on Python 2.4.3) under Win32:: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 Type help, copyright, credits or license for more information. a = 1e300 * 1e300 a 1.#INF b = 1e6 b 1.#INF a == b True c = a - a c -1.#IND d = b - b d -1.#IND c == d False c == c False b == b True a == a True a is a True b is b True c is c True d is d True Thanks, -- Pierre Rouleau -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting recursion loops
Hi! I hope you are not trying to find infinite loops and I simply misunderstood your question. Because if you are, then forget it (Turing anyone?)... Infinite loops are impossible to find (minus some few, very specific situations). Cf. http://en.wikipedia.org/wiki/Halting_problem Cheers, Hugo Ferreira P.S. Hmmm... It seems I really read it wrong since you define that you want to stop (after N passes or some complex criteria). Anyway I leave the warning for future generations :) My code does recursion loops through a couple of functions. Due to problematic I/O input this leads sometimes to endless recursions and after expensive I/O to the Python recursion exception. What would be a good method to detect recursion loops and stop it by user-Exception (after N passes or some complex criteria) without passing a recursion counter parameter through all the funcs? Robert -- http://mail.python.org/mailman/listinfo/python-list
Re: Surprise with special floating point values
On Nov 29, 12:53 pm, [EMAIL PROTECTED] wrote: Hi all, While trying to use simplejson under Python 2.4.3 I have been investigating the handling of special floating point values and found that both Python 2.4 and 2.5 return False when comparing a NaN with itself. Although surprising, I imagine it could also be correct since NaN is not a number. But is it correct? And of course it is correct... As NaN does not compare with itself in floating point: http://en.wikipedia.org/wiki/NaN Should have read it earlier... -- Pierre Rouleau -- http://mail.python.org/mailman/listinfo/python-list
Re: pickle and infinity
Bart Ogryczak wrote: I´ve got this problem with pickle, it seems it doesn´t handle correctly infinite values (nor does Python return overflow/underflow error). Python 2.X relies on the C library to serialize floats, and, as you've noticed, some C libraries can produce values that they themselves cannot read. /F -- http://mail.python.org/mailman/listinfo/python-list
Re: pyxpcom
Trent Mick wrote: hg wrote: Trent Mick wrote: My need is as follows: I have developed an activex component to access a smart card on the client side / do some web site logon. Are xpcom / pyxpcom advanced/stable enough for such an implementation under Linux / Windows ? You mean to provide the equivalent functionality for Firefox that your activex component does for IE? Yes, xpcom and pyxpcom are quite stable, however putting together a Firefox extension that gets PyXPCOM itself up and running in a client's Firefox install will be quite challenging. Trent Exactly ... are you saying I need to distribute Firefox compiled differently in order to achieve that ? No. But you'll have to get comfortable building your own Firefox and then building the PyXPCOM extension and then packaging the built PyXPCOM bits that a normal Firefox install does not have already into a Firefox extension. This would also mean packaging up parts of a Python build and possible needing to have a custom Python build to (1) get shared library loading to work correct and (2) ensure there isn't crosstalk between the python that PyXPCOM uses and possibly other Python installations on the target machine. This is less a python issue clearly if that is the case: would I have the same issues to resolve if I were to write the module in C++ ? A little, yes: I believe you'd need a Firefox build in a development tree to build a vanilla C++ XPCOM component. However, I am not sure of that. Mostly, no: You wouldn't need to worry about all the PyXPCOM/Python build/install issues. Trent Thanks Trent, I'll do some testing and bug Mark in the process I'm sure :-) Regards, Philippe -- http://mail.python.org/mailman/listinfo/python-list
Re: Surprise with special floating point values
[EMAIL PROTECTED] wrote: While trying to use simplejson under Python 2.4.3 I have been investigating the handling of special floating point values note that JSON doesn't support non-numeric floating point values, as can be seen by the number syntax description on this page: http://www.json.org/ (and as I pointed out in another thread on this topic, Python relies on the C library for serialization of floats, so non-numeric floating point values aren't portable between Python versions either). /F -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting recursion loops
Rob Wolfe wrote: robert wrote: My code does recursion loops through a couple of functions. Due to problematic I/O input this leads sometimes to endless recursions and after expensive I/O to the Python recursion exception. What would be a good method to detect recursion loops and stop it by user-Exception (after N passes or some complex criteria) without passing a recursion counter parameter through all the funcs? What about `sys.setrecursionlimit`? http://docs.python.org/lib/module-sys.html That is a low level barrier. I just want to limit a certain recursion call chain. -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting recursion loops
Carl Banks wrote: robert wrote: My code does recursion loops through a couple of functions. Due to problematic I/O input this leads sometimes to endless recursions and after expensive I/O to the Python recursion exception. What would be a good method to detect recursion loops and stop it by user-Exception (after N passes or some complex criteria) without passing a recursion counter parameter through all the funcs? 1. You could catch RuntimeError at the top, check whether it's recursion depth exception, and raise a user exception if it is. thats what happens now anyway. need to limit this kind of recursion. 2. Consider whether you're unwittingly trying to cover up a bug. ISTM no matter how problematic the input is, you should at least be able to make progress on it. Are you getting this error because, say, you're not incrementing a counter somewhere, and thus recalling a function with the same arguments again? the bug comes in from the I/O input. its about to stop it in non-simple recursion (through more functions calls) 3. Also consider whether you could rewrite the code to be non-recursive. Usually when I process input recursively, the input is allowed to be arbitrarily deeply nested. (In that case I think it would be a mistake to arbitrarily limit depth.) But it sounds to me like your input might be inherently non-nestable. If that's the case, it might be possible to get rid of the recursion altogether, or at least to put in error checking that detects when input is at an invalid depth. 4. If those concerns don't apply, and you do need to detect recursion, I'd suggest using a global dictionary to track function calls. If you have a function parse_something that you want to track, you could define a dict like this: _call_count = { parse_something: 0 } And change parse_something to adjust its own counter: def parse_something(): _call_count[parse_something] += 1 check_invalid_recursion() _call_count[parse_something] -= 1 (You could define a decorator to do this more easily; that's left as an excercise.) The check_invalid_recursion() function would inspect _call_count and raise an exception based on any criteria you want. thats possibly the right practical/fast possibility, I end so far with. As its threaded, a try-finally protected counter on a TLS _func_recccount[thread.get_ident()] 5. In CPython, you could just inpect the stack frame and look for duplicated function calls. See the documentation for sys._getframe. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: pickle and infinity
Fredrik Lundh wrote: Bart Ogryczak wrote: I´ve got this problem with pickle, it seems it doesn´t handle correctly infinite values (nor does Python return overflow/underflow error). Python 2.X relies on the C library to serialize floats, and, as you've noticed, some C libraries can produce values that they themselves cannot read. Actually I´d be very happy, if Python would throw FloatPointExeption, rather then allow infinite values. Haven´t got idea how to do it. fpectl would do the trick, but it´s not present nither on Solaris, nor on Windows platform. And I´d need it on both. -- http://mail.python.org/mailman/listinfo/python-list
Re: Detecting recursion loops
robert wrote: the bug comes in from the I/O input. Have you considered checking your input for valid values? Cheers, John -- http://mail.python.org/mailman/listinfo/python-list
SPE refuses.
According to apt-show-versions I have installed: python-wxgtk2.6 2.6.3.2.1.5 spe 0.8.2a+repack-1 However when I start SPE I get the message You need to install at least wxPython v2.5.4.1 to run SPE How do I tell SPE that I have the right wxPython ? e. -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 -- http://mail.python.org/mailman/listinfo/python-list
Re: OODB vs RDBMS
Thomas Guettler wrote: Hi, most of the time I use ZODB/Durus to store my data. I like it, but I know that it has some weaknesses: - only accesible from python - I need to code your indexes for fast searching yourself. There are other features of relational database systems that I find much more relevant than those, but then I don't know what your use case is. For high performance, mission critical, multi-user database systems, where many simultaneous users actually do fine grained data manipulation, I don't think there is any competition. Also, I don't know any other solution that lets you do serious tuning without code changes. Even if the application is the same, data size and usage patterns might lead to vastly different performance. Being able to speed up some operation on the expense of some other operations might be just the right thing for a certain installation at a certain time. This can be more or less automatic, depending on your brand and version of RDBMS. For a non-critical, single-user system without huge amounts of data in a structure that fits the relational model, it might not be worth the effort. I think about using a RDBMS for the next project. What I don't like about RDBMS: If you need a list of values you need to create a new table. Example: If you want to store several email addresses of one customer, you need to create a new table. I think this is a tiny thing when you look at the big picture. I don't know a lot about the PostgreSQL extensions, but the way things work in relational database has proven to work very well for quite some time. Obviously, OODBMS's haven't made any huge impact, despite two decades of efforts. The impedance mismatch between OO programming and relational databases is annoying, but it's something we have to (and can) deal with. Since the namespace if tablenames is flat, you soon have so many tables, that it is hard to browse them. The tablename namespace is not flat in SQL. Where did you get this from? Although not implemented in every RDBMS, the SQL standard has the concept of a schema, and every table should belong to a schema. For instance Oracle lacks schemata, but more or less makes up for it by through the way it implements users. (Tables are owned by users.) There's just this two level structure though, no abitrary hierarchy. Postgres has extensions which allows you to store arrays in a column. Is this supported by the python binding? Are there other databases which support this? I don't know about the first question, but regarding the second, none of the popular ones do as far as I know. PostrgeSQL is a fine RDBMS though. By the way, a database is a collection of data, not some software. Are there OR-mappers (object relational mappers) which support lists in a column? I think they do, but having a separate class for the email addresses (if we continue with your example above) has its advantages too. If the customer has several email addresses (and you feel a desire to keep track of that) they are probably different in some ways. It's e.g. likely that you should use one particular address as recipient when you send mail, not just one at random, or all of them. You might also realize than not only customers, but also other entities, such as employees, sub-contractors and authorities have email addresses. Actually, while you might get more tables due to the first normal form, your tables might well get leaner, the total amount of columns smaller, and your over-all datamodel more coherent. How is the unicode support of the python bindings to RDBMSs? I don't want to convert the results of a query to unicode myself. Can you insert unicode strings into a SELECT statement? As far as I remember, all the bindings I tried returned unicode objects from varchar and char fields, and always accepted them as parameters for CHAR/VARCHAR fields. Remember to always pass parameters properly. I.e. use e.g. cur.execute(SELECT * FROM T WHERE C=?, col_value) rather than something like cur.execute(SELECT * FROM T WHERE C=+col_value). The former will prevent SQL injection attacks, remove the need to worry about quoting and escaping, and also make performance better in the major systems. -- http://mail.python.org/mailman/listinfo/python-list
RE: Python work in UK
The technical director of Cabletron used to write applications in Python, then give the working product/code to the development group to convert. Perhaps you could build stuff in Python and outsource the conversion to India? -Original Message- From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] Behalf Of Steven Wayne Sent: Friday, November 24, 2006 10:42 AM To: python-list@python.org Subject: Re: Python work in UK On Thu, 23 Nov 2006 19:28:26 +, Will McGugan [EMAIL PROTECTED] wrote: Hi, I'd love to work in Python, for the sake of my blood pressure, but there doesnt seem to be that many jobs that look for Python as the main skill. I use Python at work from time to time, and occasionaly get to spend several days on a Python project but the majority of the time I use C++. How can I make that leap to working with Python? There doesn't seem to be many UK positions on the jobs section of Python.org or the usual jobs sites. Any recommended jobs sites or tips? (I have googled) In the off chance that a potential empolyer is reading this, I'm looking for something in web development, applications, graphics or other interesting field. Here is a copy of my CV. http://www.willmcgugan.com/cvwillmcgugan.pdf Regards, Will McGugan www.riverhall.co.uk are looking. Steven -- .''`. : :' : `. `'` `- -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Re: Surprise with special floating point values
On Nov 29, 1:11 pm, Fredrik Lundh [EMAIL PROTECTED] wrote: [EMAIL PROTECTED] wrote: While trying to use simplejson under Python 2.4.3 I have been investigating the handling of special floating point valuesnote that JSON doesn't support non-numeric floating point values, as can be seen by the number syntax description on this page: http://www.json.org/ (and as I pointed out in another thread on this topic, Python relies on the C library for serialization of floats, so non-numeric floating point values aren't portable between Python versions either). /F That's true, but I ran into a problem with simplejson under Python 2.4.3 on Win32, where it fails to serialize 1.0 properly (and I reported the problem to its author, and the fact that it works fine under Python 2.5). There is another thread (Inconsistency producing constant for float infinity) that talks about differences between Python 2.5 and earlier versions regarding treatment of non-numeric floating point values. So, while investigating the simplejson problem, I though I had found a problem with the handling of NaN (which obviously is not the case). - Pierre R. -- http://mail.python.org/mailman/listinfo/python-list
Re: SPE refuses.
If wxPython is rightly installed, which means that import wx works fine and wx.VERSION gives the right version, you can ignore the wxPython warning. Please cd do your site-packages directory and do python SPE.py --debug and see the error message. Stani On 29 nov, 19:51, egbert [EMAIL PROTECTED] wrote: According to apt-show-versions I have installed: python-wxgtk2.6 2.6.3.2.1.5 spe 0.8.2a+repack-1 However when I start SPE I get the message You need to install at least wxPython v2.5.4.1 to run SPE How do I tell SPE that I have the right wxPython ? e. -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 -- http://mail.python.org/mailman/listinfo/python-list
Re: libboost, python, and dijkstra shortest path
Ok, found the solution here: http://www.osl.iu.edu/~dgregor/bgl-python/ But still cannot make anything that works... Anyone who has experience in this area can help me with the following code: import boost as bgl graph = bgl.Graph() a = graph.add_vertex() b = graph.add_vertex() e = graph.add_edge(a, b) weights = graph.edge_property_map('integer') weights[e] = 5 graph.edge_properties['weight'] = weights boost.dijkstra_shortest_paths(graph, a) On Nov 29, 5:51 pm, Bytter [EMAIL PROTECTED] wrote: Hi everyone, I need to implement a very quick (performance-wise) Dijkstra shortest path in python, and found that libboost already has such thing. Problem is: I cannot find the installation package for my Python 2.4 under windows. Can someone please provide me instructions for installing libboost for python? In alternative, if someone can point out to a fast Dijkstra shortest path in python (the network is over 1 million vertexes), I would appreciate. Thanks in advance, Hugo Ferreira -- http://mail.python.org/mailman/listinfo/python-list
Re: why would anyone use python when java is there?
He trolls other groups as well. Smalltalk for example -- http://groups.google.com/group/comp.lang.smalltalk/browse_thread/thread/1c83e576be824633/927227555661a2cd?lnk=gstq=gavinornum=1#927227555661a2cd. There are at least a dozen recent posts where he asks some obvious trollling line of questioning... Adam Jones wrote: gregarican wrote: gavino wrote: wtf You have to be trolling I would think. Yeah, gavino has been trolling comp.lang.lisp for quite some time. For the life of me I can't understand why he would troll comp.lang.python when comp.lang.lisp is there. -Adam -- http://mail.python.org/mailman/listinfo/python-list
buildbot
does anyone know if processes defined around buildbot would be similar to the one used by the mozilla seamonkey project which uses tinderbox? this link shows an example of an entire checkin cycle using tinderbox and it's quite detailed and gives a very good picture of what using the product would be like. http://www.mozilla.org/hacking/working-with-seamonkey.html i know python is currently using buildbot... are there any differences or simplifications in the processes using buildbot? thanks, bryan -- http://mail.python.org/mailman/listinfo/python-list