From ptmcg at austin.rr.com Mon Mar 21 03:10:56 2005 From: ptmcg at austin.rr.com (Paul McGuire) Date: 21 Mar 2005 00:10:56 -0800 Subject: Text-to-speech References: <61986976a626d1ea12d840b72f4b1a2a@conncoll.edu> <423DE896.4020807@holdenweb.com> Message-ID: <1111392656.371303.93810@z14g2000cwz.googlegroups.com> How about a clerihew instead of a limerick? Guido van Rossum Had an idea most awesome. When he lost track of his braces, Just replaced them with spaces. -- Paul McGuire From rkern at ucsd.edu Sun Mar 13 01:39:05 2005 From: rkern at ucsd.edu (Robert Kern) Date: Sat, 12 Mar 2005 22:39:05 -0800 Subject: Overloading the "and" operator In-Reply-To: <31f7e57d.0503122133.b9073e1@posting.google.com> References: <31f7e57d.0503122133.b9073e1@posting.google.com> Message-ID: Fredrik Bertilsson wrote: > I am trying to overload the "and" operatior, but my __and__ method is > never called. __and__ overloads the "&" operator. The "and" keyword cannot be overloaded. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From mefjr75 at hotmail.com Thu Mar 17 16:12:34 2005 From: mefjr75 at hotmail.com (M.E.Farmer) Date: 17 Mar 2005 13:12:34 -0800 Subject: Simple account program References: <3c3f0fe410f2634f32a0dff4156de59d@localhost.talkaboutprogramming.com> Message-ID: <1111093953.982736.105620@z14g2000cwz.googlegroups.com> Igorati, I wished I could give you a simple fix, BUT... You need to really re-read the docs and do some tutors first . Your understanding of classes and namespaces is flawed and will not become clear without futher study. search strategy: python namespaces python class python tutor Classes are like containers. Classes have there own namespace, "self". Multiple classes do not share namespaces. Stay away from inheritance till you have an understanding of namespace, no need in getting mixed up. Withdrawl, Deposit, Transaction should be members of the account class. That way they can share a namespace and simplify your design. Why do you need to search a pickle? Pickle an instance of the class and unpickle it when needed and your data will be however it was in your instance. If you have real code post it because this code does not work and never will. Quit posting homework, you can ask for occasional help, but this is the third time i have seen this, it is getting worse and you have been warned before ;) Surely in the month since you first asked you could have read a bit of documentation. # this is not complete or even tested it is just an example ( based on your code ) import time class Account: def __init__(self, initial): self.balance = initial self.history = {} def deposit(self, amt): self.balance = self.balance + amt self.save('deposit',amt) def withdraw(self, amt): self.balance = self.balance - amt self.save('withdrawl', amt) def getbalance(self): return self.balance def gethistory(self): return self.history def save(self,trans,amount): # store the transaction type, amount, balance self.history[self.timestamp()] = (trans,amount,self.balance) def timestamp(self): return time.asctime() def transaction(self): withdrawl = raw_input("Is this a deposit or withdrawl?") amount = raw_input("Please enter amount here.") if withdrawl.lower() in ["withdrawl","w"]: self.withdraw(amount) else: self.deposit(amount) hth, M.E.Farmer From rupole at hotmail.com Sat Mar 5 15:07:24 2005 From: rupole at hotmail.com (Roger Upole) Date: Sat, 5 Mar 2005 15:07:24 -0500 Subject: Win32 drive mapping... aka "net use" References: <8lr9nc$tdf$1@nnrp1.deja.com> <1110044817.235507.299580@o13g2000cwo.googlegroups.com> <422a0791$1_2@127.0.0.1> <1110051935.541036.146070@z14g2000cwz.googlegroups.com> Message-ID: <422a1227$1_2@127.0.0.1> The split should work fine if you remove the r (raw string) prefix. >>> win32api.GetLogicalDriveStrings().split('\\\x00') ['A:', 'C:', 'D:', 'E:', 'F:', 'G:', 'H:', 'J:', 'K:', 'Y:', 'Z:', ''] Roger "Lucas Machado" wrote in message news:1110051935.541036.146070 at z14g2000cwz.googlegroups.com... > Roger Upole wrote: >> You could use win32api.GetLogicalDriveStrings to list >> the drive letters currently in use, and find the next free >> letter. net use * probably does something like that under >> the covers. > > I went and took your advice and this is where I am now: > >>>> import win32api >>>> a = win32api.GetLogicalDriveStrings() >>>> a > 'A:\\\x00C:\\\x00D:\\\x00E:\\\x00Z:\\\x00' >>>> print a > A:\ C:\ D:\ E:\ Z:\ > > So I think this function will work great since it gives me a string > that i can simply strip away what i don't need and then split it into a > list and traverse the list. However, when I try to split it, the > following occurs: > >>>> b = a.strip(r'\\\x00') >>>> b > 'A:\\\x00C:\\\x00D:\\\x00E:\\\x00Z:\\\x00' >>>> b = a.split(r'\\\x00') >>>> b > ['A:\\\x00C:\\\x00D:\\\x00E:\\\x00Z:\\\x00'] > > I'm a bit of a novice at python (even more so of the win32 api), but > I've used the split and strip functions before (for example to get rid > of '\n' from strings) so it is unclear to me why this does not work. > > Thanks > --LM > ----== Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet News==---- http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ Newsgroups ----= East and West-Coast Server Farms - Total Privacy via Encryption =---- From mahs at telcopartners.com Tue Mar 29 22:23:12 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 29 Mar 2005 19:23:12 -0800 Subject: automatically mapping builtins (WAS: itertools to iter transition) In-Reply-To: <8eadnSR6KpjyTNTfRVn-1w@comcast.com> References: <8eadnSR6KpjyTNTfRVn-1w@comcast.com> Message-ID: Steven Bethard wrote: > Michael Spencer wrote: > > While we're on the topic, what do you think of having unary, > > non-summary builtins automatically map themselves when called with an > > iterable that would otherwise be an illegal argument: > > I personally don't much like the idea because I expect 'int' to produce > an int, just like I expect 'list' to produce a list. So having 'int' > produce an iterable in any situation seems inappropriate to me. > > [...] > Bengt Richter wrote: > That last "otherwise" is pretty important for strings as in int('1234') ;-) > [snip] > > But wouldn't you really currently write the "->" form from above? I.e., > > for ordchar in (ord(c) for c in somestring): > ... > Thanks for the reactions, (and test implementation, Bengt) Something to play with, but the idea doesn't seem like a big win, when the explicit genexp is fully general and only slightly more verbose. Michael From misthunter at gmail.com Sat Mar 26 12:02:56 2005 From: misthunter at gmail.com (R.Meijer) Date: Sat, 26 Mar 2005 17:02:56 +0000 (UTC) Subject: The Greatest News Ever! References: <1111850237.833223.239800@l41g2000cwc.googlegroups.com> Message-ID: yahoo.com> writes: > > http://www.jcil.blogspot.com << The Greatest News Ever! > Wow, what a total bullshit (no offense to christians >_> ) Now, what I don't understand is what this is doing in a python newsgroup? From harlinseritt at yahoo.com Sun Mar 13 05:22:07 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 13 Mar 2005 02:22:07 -0800 Subject: Searching for a ComboBox for Tkinter? Message-ID: <1110709327.002537.56300@o13g2000cwo.googlegroups.com> I've created a ghetto-ized ComboBox that should work nicely for Tkinter (unfortunately no dropdown capabilities yet). I've found why it's such a pain in the @ss to create one. You have to re-create common methods and make sure they're mapped to the right component (inside this widget are frame, entry, listbox, and scrollbar widgets). I tried to look for ways I could inherit some methods from other widgets but couldn't think of how to do it in an efficient way. If anyone has suggestions to improve it, please respond... Remember... I'm a traditional c/c++ turned python programmer who forgets that there usually is a better, faster more graceful way to do things with Python than with C/C++/Java. Cheers, Harlin ###################################################################### # Seritt Extensions: # Date: 02262005 # Class ComboBox # Add this section to your Tkinter.py file in 'PYTHONPATH/Lib/lib-tk/' # Options: width, border, background, foreground, fg, bg, font # , relief, cursor, exportselection, selectbackgroun, selectforeground, height # # Methods: activate(int index) => int, curselection() => int, delete(item=["ALL" or int], start=int, end=["END" or # int], # focus_set()/focus(), get()=>selected string in box, pack(padx=int, pady=int, fill(X, Y, BOTH), expand=bool, # side=LEFT, # RIGHT, TOP, BOTTOM, CENTER # class ComboBox: ITEMS = range(0) def activate(self, index): self.listbox.activate(index) def curselection(self): return map(int, self.listbox.curselection())[0] def delete(self, item=None, start=None, end=None): if item=='ALL': self.listbox.delete(0, END) elif start == None and end == None: self.listbox.delete(item) else: self.listbox.delete(start, end) def get_focus(self): self.entry.get_focus() def focus(self): self.entry.get_focus() def get(self): return self.entry.get() def pack(self, padx=None, pady=None, fill=None, expand=None, side=None): self.frame.pack(padx=padx , pady=pady , fill=fill , expand=expand , side=side) def size(self): return self.listbox.size() def insert(self, START, ITEM): self.ITEMS.append(ITEM) self.listbox.insert(START, ITEM) self.listbox.select_set(0) self.entry.delete(0, END) self.entry.insert(0, self.listbox.get(self.listbox.curselection())) def change_entry(self, event): def i(event): try: self.entry.delete(0, END) self.entry.insert(0, self.listbox.get(self.listbox.curselection())) except: pass self.listbox.bind("", i) def __init__(self, parent, width=None, border=1, background=None, foreground=None, fg=None, bg=None, font=None , relief=None, cursor=None, exportselection=None, selectbackgroun=None, selectforeground=None, height=None): self.frame = Frame(parent) self.entry = Entry(self.frame , width=None , border=border , background=background , foreground=foreground , fg=fg , bg=bg , font=font , relief=relief , cursor=cursor , exportselection=exportselection , selectbackgroun=selectbackgroun , selectforeground=selectforeground , height=height) self.entry.pack(fill=X) self.scroll = Scrollbar(self.frame) self.scroll.pack(side=RIGHT, fill=Y) self.listbox = Listbox(self.frame , yscrollcommand=self.scroll.set , width=None , border=border , background=background , foreground=foreground , fg=fg , bg=bg , font=font , relief=relief , cursor=cursor , exportselection=exportselection , selectbackgroun=selectbackgroun , selectforeground=selectforeground , height=height) self.listbox.pack(fill=X) self.scroll.config(command=self.listbox.yview) self.listbox.bind("", self.change_entry) From lbates at syscononline.com Thu Mar 3 11:42:44 2005 From: lbates at syscononline.com (Larry Bates) Date: Thu, 03 Mar 2005 10:42:44 -0600 Subject: binutils "strings" like functionality? In-Reply-To: <1109858503.101635.185640@l41g2000cwc.googlegroups.com> References: <1109858503.101635.185640@l41g2000cwc.googlegroups.com> Message-ID: <3_mdnaAlNYcbo7rfRVn-2w@comcast.com> Take a look at python's struct module in the standard library. Many people use it to manipulate binary objects at the byte level with great success. Larry Bates cjl wrote: > Hey all: > > I am working on a little script that needs to pull the strings out of a > binary file, and then manipulate them with python. > > The command line utility "strings" (part of binutils) has exactly the > functionality I need, but I was thinking about trying to implement this > in pure python. > > I did some reading on opening and reading binary files, etc., and was > just wondering if people think this is possible, or worth my time (as a > learning exercise), or if something like this already exists. > > -cjl > From peter at engcorp.com Wed Mar 23 12:02:02 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 23 Mar 2005 12:02:02 -0500 Subject: os.stat access and modify time same on WinXP In-Reply-To: References: Message-ID: rbt wrote: > I'm using the standard NTFS file system. The only time the access time > is updated is when the file is modified or saved (with no changes). > What's up with that? Shouldn't a read/view update the access time? See http://www.microsoft.com/resources/documentation/Windows/XP/all/reskit/en-us/Default.asp?url=/resources/documentation/Windows/XP/all/reskit/en-us/prkc_fil_punq.asp Quoting: ''' The Last Access Time on disk is not always current because NTFS looks for a one-hour interval before forcing the Last Access Time updates to disk. NTFS also delays writing the Last Access Time to disk when users or programs perform read-only operations on a file or folder, such as listing the folder's contents or reading (but not changing) a file in the folder. If the Last Access Time is kept current on disk for read operations, all read operations become write operations, which impacts NTFS performance. Note * File-based queries of Last Access Time are accurate even if all on-disk values are not current. NTFS returns the correct value on queries because the accurate value is stored in memory. ''' Does that help? (Just went through this myself the other day.) -Peter From lbates at syscononline.com Wed Mar 30 09:01:52 2005 From: lbates at syscononline.com (Larry Bates) Date: Wed, 30 Mar 2005 08:01:52 -0600 Subject: twistedSnmp and hexadecimal values ... In-Reply-To: References: Message-ID: You really should give an example so that we will know what you mean by "weird and useless". Otherwise you are asking us to implement TwistedSnmp to see what you are referring to. Larry Bates Francesco Ciocchetti wrote: > Hi all ml. > > I'm tryng to use TwistedSnmp to make query and walk directly inside my > python code. > > The problem i'm facing is that any time there is an hexadecimal value to > be returned by the snmpwalk it is returened in a weird and useless > way... does anyone had any (successfull) experience with twistedsnmp and > hexadecimal values (as Mac Addresses)? > > thanks >

> From vetter at lincom-asg.com Fri Mar 25 12:16:45 2005 From: vetter at lincom-asg.com (Keith) Date: 25 Mar 2005 09:16:45 -0800 Subject: Version Number Comparison Function In-Reply-To: References: <1111764878.482502.69390@g14g2000cwa.googlegroups.com> Message-ID: <1111771005.667124.297260@f14g2000cwb.googlegroups.com> distutils is one of the places I looked: http://www.python.org/doc/2.3.5/lib/module-distutils.html But I didn't see the functions documented. I am new to Python so I didn't know where else to look. Using distutils seems like it would be the most generic and supported way to compare version numbers. From simon.brunning at gmail.com Mon Mar 14 12:22:14 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Mon, 14 Mar 2005 17:22:14 +0000 Subject: python reading excel thru ADO ? In-Reply-To: <5RiZd.3702$qW.3701@newsread3.news.atl.earthlink.net> References: <5RiZd.3702$qW.3701@newsread3.news.atl.earthlink.net> Message-ID: <8c7f10c605031409222293a437@mail.gmail.com> On Mon, 14 Mar 2005 16:20:17 GMT, Chris Curvey wrote: > I've been reading http://www.mayukhbose.com/python/ado/ad-connection.php > , which seems to infer that I can read an Excel file using the ADO > interface with Python on Windows. Unfortunately, the usual problem with > ADO -- connection strings -- is raising it's ugly head. > > Has anyone made this work, and would you share the connection string > that you used? Never tried it, I'm afraid. No, strike that. I'm actually pretty glad that I've never tried it. ;-) But in any case this might help: http://www.connectionstrings.com/ -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From sjmachin at lexicon.net Tue Mar 1 19:10:10 2005 From: sjmachin at lexicon.net (John Machin) Date: 1 Mar 2005 16:10:10 -0800 Subject: Canonical way of dealing with null-separated lines? In-Reply-To: References: <5aes11d4da95un1n78vtb04m43269hqo4m@4ax.com> <1109642538.040399.60890@z14g2000cwz.googlegroups.com> Message-ID: <1109722210.590554.211030@l41g2000cwc.googlegroups.com> Douglas Alan wrote: > "John Machin" writes: > > >> lines = (partialLine + charsJustRead).split(newline) > > > The above line is prepending a short string to what will typically be a > > whole buffer full. There's gotta be a better way to do it. > > If there is, I'm all ears. In a previous post I provided code that > doesn't concatinate any strings together until the last possible > moment (i.e. when yielding a value). The problem with that the code > was that it was complicated and didn't work right in all cases. > > One way of solving the string concatination issue would be to write a > string find routine that will work on lists of strings while ignoring > the boundaries between list elements. (I.e., it will consider the > list of strings to be one long string for its purposes.) Unless it is > written in C, however, I bet it will typically be much slower than the > code I just provided. > > > Perhaps you might like to refer back to CdV's solution which was > > prepending the residue to the first element of the split() result. > > The problem with that solution is that it doesn't work in all cases > when the line-separation string is more than one character. > > >> for line in lines: yield line + outputLineEnd > > > In the case of leaveNewline being false, you are concatenating an empty > > string. IMHO, to quote Jon Bentley, one should "do nothing gracefully". > > In Python, > > longString + "" is longString > > evaluates to True. I don't know how you can do nothing more > gracefully than that. And also "" + longString is longString The string + operator provides those graceful *external* results by ugly special-case testing internally. It is not graceful IMHO to concatenate a variable which you already know refers to a null string. Let's go back to the first point, and indeed further back to the use cases: (1) multi-byte separator for lines in test files: never heard of one apart from '\r\n'; presume this is rare, so test for length of 1 and use Chris's simplification of my effort in this case. (2) keep newline: with the standard file reading routines, if one is going to do anything much with the line other than write it out again, one does buffer = buffer.rstrip('\n') anyway. In the case of a non-standard separator, one is likely to want to write the line out with the standard '\n'. So, specialisation for this is indicated: ! if keepNewline: ! for line in lines: yield line + newline ! else: ! for line in lines: yield line Cheers, John From jjesso at global-matrix.com Tue Mar 8 12:46:56 2005 From: jjesso at global-matrix.com (jjesso at global-matrix.com) Date: 8 Mar 2005 09:46:56 -0800 Subject: logging addLevelName Message-ID: <1110304016.776652.255810@l41g2000cwc.googlegroups.com> I am trying to add a new logging level. logging.config.fileConfig("bengineLog.cfg") logging.CLIENT = logging.INFO + 1 logging.addLevelName( logging.CLIENT, 'CLIENT' ) logging.root.setLevel( [logging.INFO, logging.CLIENT, logging.WARNING, logging.ERROR, logging.CRITICAL] ) logger = logging.getLogger(None) logging.Logger.client('test') I get error: AttributeError: class Logger has no attribute 'client' Any help? From jasmin at soton.ac.uk Fri Mar 11 09:31:25 2005 From: jasmin at soton.ac.uk (jasmin at soton.ac.uk) Date: 11 Mar 2005 06:31:25 -0800 Subject: help with warning formatting In-Reply-To: <3e429f3f$1_1@omega.dimensional.com> References: <3e429f3f$1_1@omega.dimensional.com> Message-ID: <1110551485.390771.104150@f14g2000cwb.googlegroups.com> > import warnings > warnings.warn('foo') > > % python t.py > t.py:2: UserWarning: foo > warnings.warn('foo') > > Is there a way to just issue the warning message itself, or to at least > suppress printing the line where the warning occurred (" > warnings.warn('foo')" in the example)? In case anyone else is searching for a solution to this the following sort of works in Python 2.1: warnings.warn_explicit('foo', UserWarning, '', '') :: UserWarning: foo I'm new to Python so if there is a better way to do this please let me know. Jasmin From steven.bethard at gmail.com Wed Mar 16 11:59:53 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 16 Mar 2005 09:59:53 -0700 Subject: Mark attribute as read-only In-Reply-To: <7eb83f4a.0503160839.e259542@posting.google.com> References: <7eb83f4a.0503160839.e259542@posting.google.com> Message-ID: Florian Lindner wrote: > how can I mark a attribute of a class as read-only (for non classmembers)? > Yes, stupid question, but the docu gave me no help. Declare it as such in the documentation. ;) If you want to provide error messages, you could alternatively define a property: py> class C(object): ... def _getx(self): ... return self._x ... x = property(fget=_getx) ... def __init__(self, x): ... self._x = x ... py> c = C(4) py> c.x 4 py> c.x = 6 Traceback (most recent call last): File "", line 1, in ? AttributeError: can't set attribute STeVe From news at trevp.net Wed Mar 23 00:23:15 2005 From: news at trevp.net (news at trevp.net) Date: 22 Mar 2005 21:23:15 -0800 Subject: XML/RPC server with SSL in Python References: <4240734d.7099468@news.t-online.de> Message-ID: <1111555395.780688.50480@z14g2000cwz.googlegroups.com> Gerson Kurz wrote: > Are there any alternatives to using M2Crypto for an XML/RPC server in > SSL in Python? tlslite supports SocketServers like SimpleXMLRPCServer: http://trevp.net/tlslite Trevor From charles.hartman at conncoll.edu Sun Mar 20 16:49:37 2005 From: charles.hartman at conncoll.edu (Charles Hartman) Date: Sun, 20 Mar 2005 16:49:37 -0500 Subject: Software for Poets (Was: Re: Text-to-speech) In-Reply-To: <200503202210.48477.francis.girard@free.fr> References: <61986976a626d1ea12d840b72f4b1a2a@conncoll.edu> <200503202210.48477.francis.girard@free.fr> Message-ID: <4e2825b08079ca53096abf273bba3ca9@conncoll.edu> On Mar 20, 2005, at 4:10 PM, Francis Girard wrote: > Hello M. Hartman, > > It's a very big opportunity for me to find someone that both is a poet > and > knows something about programming. > > First, please excuse my bad english ; I'm a french canadian. My French is a great deal worse than your English; fear not. > > I am dreaming to write a software to help french poets to write strict > rigourous classical poetry. Since calssical poetry is somewhat > mathematical, > a lot of tasks can be automatised : > > 1- Counting the number of syllabs ("pied" in french) in a verse > > 2- Checking the rimes ; determining the strength of a rime > > 3- Checking compliance of a poem to a fixed pre-determined classical > form (in > french, we have distique, tercet, quatrain, quintain, sixain, huitain, > dizain, triolet, vilanelle, rondeau, rondel, ballade, chant royal, > sonnet, > etc.) > > 4- Propose a synonym that will fit in a verse, i.e. with the right > amount of > syllabs > > 5- Suggest a missing word or expression in a verse by applying the > Shannon > text generation principle > > First, do you think it may be a useful tool ? That is a very deep question. (See below.) > What other features you think can make it usefull for a poet ? > > The first task of cutting sentences into syllabs (phonetically of > course, not > typographically) is already done. It's been difficult to get it right > and to > make it guess correctly with a very very high percentage. > > I can very well imagine that the next task is even more difficult. I > need to > translate text into phonems. Do you know some software that does it ? > I guess > that voice synthetisers that translates written text into spoken text > must > first translate the text into phonems. Right ? Do you know if there > some way > that I can re-use some sub-modules from these projects that will > translate > text into phonems ? The problems are hard ones. Getting reliable syllable divisions is, all by itself, a heart-breaker in English; I'm not sure whether harder or easier in French. (See the module syllables.py in the source code to my Scandroid program at the site listed below.) Rhyme is harder -- I haven't yet tried it in English -- precisely because text-to-phoneme is very hard. I haven't really worked with this, that is, with the sounds of speech (though I'm a musician as well as a poet), mostly because it's difficult. The projects in my *Virtual Muse: Experiments in Computer Poetry"[1], for example, deal almost entirely with language as a typographical phenomenon. So does my Scandroid, even though the material it's working with is all aimed at and motivated by the auditory qualities of poetry. I do imagine you're right that the text-to-speech people have worked out a lot of this. The trouble is that so far I haven't seen public-domain code for the guts of such a program, which is what you would need. Interesting to think about which problems change between French and English and which do not. Good luck -- keep me posted. [1] This was published by Wesleyan Univ Press, what, nine years ago. Probably out of print. I do know where to get some copies. From tjreedy at udel.edu Thu Mar 10 16:21:15 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 10 Mar 2005 16:21:15 -0500 Subject: Iterate using tuple as index References: <200503101312.31615.jstroud@mbi.ucla.edu> Message-ID: "James Stroud" wrote in message news:200503101312.31615.jstroud at mbi.ucla.edu... > Its not obvious to me how to do this. I would like to iterate using a > tuple as > an index. Say I have two equivalently sized arrays, what I do now seems > inelegant: Sounds like you want zip(firstlist, secondlist). If not, I somehow missed something. TJR From tinuviel at sparcs.kaist.ac.kr Tue Mar 29 10:06:58 2005 From: tinuviel at sparcs.kaist.ac.kr (Seo Sanghyeon) Date: Wed, 30 Mar 2005 00:06:58 +0900 Subject: Table of Python Packages, updated Message-ID: <20050329150658.GA846@sparcs.kaist.ac.kr> Hello, comp.lang.python, and catalog-sig, Some of you may remember my mail with the very same subject last year. :-) I have continued to maintain the table, and here's the updated result: http://sparcs.kaist.ac.kr/~tinuviel/pypackage/list.cgi 304 Python projects indexed, with links to PyPI, FreeBSD port, Debian deb, Gentoo ebuild, NetBSD pkgsrc, and Fink. Now I am thinking about adding the version tracking. What do you think? If you have any suggestion, correction or omission, please mail me! P.S. I'm not subscribed. Please CC. Seo Sanghyeon From coolroot at gmail.com Sun Mar 13 00:45:38 2005 From: coolroot at gmail.com (Marc H.) Date: Sun, 13 Mar 2005 00:45:38 -0500 Subject: Huge performance gain compared to perl while loading a text file in a list ...!? Message-ID: <3b53b7dc0503122145407a8827@mail.gmail.com> Hello, I recently converted one of my perl scripts to python. What the script does is simply search a lot of big mail files (~40MB) to retrieve specific emails. I simply converted the script line by line to python, keeping the algorithms & functions as they were in perl (no optimization). The purpose was mainly to learn python and see the differences with perl. Now, once the converted script was finished, I was amazed to find that the python version is running 8 times faster (800% faster!). Needless to say, I was very intrigued and wanted to know what causes such a performance gap between the two versions. So to keep my story short, after some research and a few tests, I found that file IO is mainly the cause of the performance diff. I made two short test scripts, one in perl and one in python (see below), and compared the performance difference. As we can see, the bigger the file the larger the difference in performance.... I'm fairly new to python, and don't know much of its inner working so I wonder if someone could explain to me why it is so much faster in python to open a file and load it in a list/array ? Thanks ----- #!/usr/bin/python for i in range(20): Data = open('data.test').readlines() ----- #!/usr/bin/perl for ($i = 0; $i < 20; $i++) { open(DATA, "data.test"); @Data = ; close(DATA); } ----- Running tests (data.test = 10MB text file): blop at moya blop $ time ./ftest.py real 0m6.408s user 0m4.552s sys 0m1.826s blop at moya blop $ time ./ftest.pl real 0m22.855s user 0m21.946s sys 0m0.822s ----- Running tests (data.test = 40MB text file): blop at moya blop $ time ./ftest.py real 0m26.235s user 0m18.238s sys 0m7.872s blop at moya blop $ time ./ftest.pl real 3m26.741s user 3m22.168s sys 0m3.764s From kay.schluehr at gmx.net Sat Mar 19 23:07:40 2005 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 19 Mar 2005 20:07:40 -0800 Subject: Pre-PEP: Dictionary accumulator methods In-Reply-To: <3a3ri5F63colgU1@individual.net> References: <1111260800.599813.270360@o13g2000cwo.googlegroups.com> <3a3ri5F63colgU1@individual.net> Message-ID: <1111291660.352638.251050@l41g2000cwc.googlegroups.com> George Sakkis wrote: > > -1 form me. > > > > I'm not very glad with both of them ( not a naming issue ) because i > > think that the dict type should offer only methods that apply to each > > dict whatever it contains. count() specializes to dict values that are > > addable and appendlist to those that are extendable. Why not > > subtractable, dividable or right-shiftable? Because of majority > > approval? I'm mot a speed fetishist and destroying the clarity of a > > very fundamental data structure for speedup rather arbitrary > > accumulations seems to be a bad idea. I would move this stuff in a > > subclass. > > > > Regards Kay > +1 on this. The new suggested operations are meaningful for a subset of all > valid dicts, so they > should not be part of the base dict API. If any version of this is approved, > it will clearly be an > application of the "practicality beats purity" zen rule, and the > justification for applying it in > this case instead of subclassing should better be pretty strong; so far I'm > not convinced though. > > George It is bad OO design, George. I want to be a bit more become more specific on this and provide an example: Let be a custom subclass of dict that stores only ints as keys as well as values: class intdict(dict): def __setitem__(self, key, value): assert isinstance(key, int) and isinstance(value, int) dict.__setitem__(self,key,value) or in Python3000 typeguard fashion: class intdict(dict): def __setitem__(self, key:int, value:int): dict.__setitem__(self,key,value) But still overloads appendlist() i.e. a method that does not work for any intdict is still part of it's public interface! This is really bad design and should not be justified by a "practicality beats purity" wisdom which should be cited with much care but not carelesness. Maybe also the subclassing idea I introduced falls for short for the same reasons. Adding an accumulator to a dict should be implemented as a *decorator* pattern in the GoF meaning of the word i.e. adding an interface to some object at runtime that provides special facilities. Usage: >>> d = intdict(extend=MyAccumulator) >>> hasattr(d,"tally") True >>> hasattr(d,"appendlist") False This could be generalized to other fundamental data structures as well. Regards Kay From tundra at tundraware.com Tue Mar 15 05:37:50 2005 From: tundra at tundraware.com (Tim Daneliuk) Date: 15 Mar 2005 05:37:50 EST Subject: Python becoming less Lisp-like References: <543c3153frfgbaear473m2jji40hub538k@4ax.com> <87zmx5n87e.fsf@wilson.rwth-aachen.de> <87vf7tiblj.fsf@wilson.rwth-aachen.de> X-Antivirus: avast! (VPS 0510-1, 03/11/2005), Outbound message Message-ID: In-Reply-To: X-Enigmail-Version: 0.90.0.0 X-Enigmail-Supports: pgp-inline, pgp-mime Content-Type: text/plain; charset=us-ascii; format=flowed Content-Transfer-Encoding: 7bit Nick Craig-Wood wrote: > Torsten Bronger wrote: > >> The current snapshot is a transitional Python and thus >> with some double features. The numerical types and two kinds of >> classes are examples. I'm very surprised about this, because Python >> is a production language, but I'm happy, too. > > > As long as python 2.x -> 3.x/3000 isn't like perl 5.x -> perl 6.x I'll > be perfectly happy too. > > "Less is more" is a much better philosophy for a language and having > the courage to take things out differentiates python from the crowd. > > Of course we users will complain about removals, but we'll knuckle > down and take our medicine eventually ;-) > Except that in this case, removal will also complicate code in some cases. Consider this fragment of Tkinter logic: UI.CmdBtn.menu.add_command(label="MyLabel", command=lambda cmd=cmdkey: CommandMenuSelection(cmd)) Would it not be the case that, without lambda, we will need to pollute the name space with a bunch of specialized little functions for each and every construct like this? -- ---------------------------------------------------------------------------- Tim Daneliuk tundra at tundraware.com PGP Key: http://www.tundraware.com/PGP/ From deetsNOSPAM at web.de Tue Mar 15 18:12:33 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Wed, 16 Mar 2005 00:12:33 +0100 Subject: why this error? References: Message-ID: spencer wrote: > Hi, > I'm not sure why I can't concatenate dirname() with basename(). > > Traceback (most recent call last): > File "showDir.py", line 50, in ? > print 'somthing new...', os.path.join(os.path.dirname(os.getcwd)) + > os.path.basename(os.getcwd()) > File "/usr/lib/python2.3/posixpath.py", line 119, in dirname > return split(p)[0] > File "/usr/lib/python2.3/posixpath.py", line 77, in split > i = p.rfind('/') + 1 Several errors: - os.getcwd is the _function_, you need to call them os.getcwd(), as you do in the second call to it. - the join is supposed to work on a list of arguments, like this: os.path.join("a", "b", "c") will yield a/b/c But you concatenate two strings using +, and thus have only one argument at all, which can't be joined as it is only one... -- Regards, Diez B. Roggisch From ville at spammers.com Thu Mar 17 06:10:54 2005 From: ville at spammers.com (Ville Vainio) Date: 17 Mar 2005 13:10:54 +0200 Subject: I can do it in sed... References: <1111022675.181736.82550@f14g2000cwb.googlegroups.com> Message-ID: >>>>> "John" == John Machin writes: John> You can get gnu Windows versions of awk sed and most other John> suchlike goodies off the net ... Yeah, google for 'unxutils'. Cygwin versions of these tools can be a headache sometimes. -- Ville Vainio http://tinyurl.com/2prnb From max at alcyone.com Tue Mar 8 11:39:52 2005 From: max at alcyone.com (Erik Max Francis) Date: Tue, 08 Mar 2005 08:39:52 -0800 Subject: Format strings that contain '%' In-Reply-To: <1110299937.861208.263140@f14g2000cwb.googlegroups.com> References: <1110299937.861208.263140@f14g2000cwb.googlegroups.com> Message-ID: rick_muller at yahoo.com wrote: > I'm trying to do something along the lines of > >>>> print '%temp %d' % 1 > Traceback (most recent call last): > File "", line 1, in ? > ValueError: unsupported format character 't' (0x74) at index 1 Use %%: >>> '%%temp %d' % 1 '%temp 1' -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis A wise man never loses anything if he have himself. -- Montaigne From bdesth.quelquechose at free.quelquepart.fr Tue Mar 15 16:55:48 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 15 Mar 2005 22:55:48 +0100 Subject: Python becoming less Lisp-like In-Reply-To: References: <543c3153frfgbaear473m2jji40hub538k@4ax.com> <87zmx5n87e.fsf@wilson.rwth-aachen.de> <87vf7tiblj.fsf@wilson.rwth-aachen.de> X-Antivirus: avast! (VPS 0510-1, 03/11/2005), Outbound message Message-ID: <423756a5$0$28611$636a15ce@news.free.fr> Martin Franklin a ?crit : > Tim Daneliuk wrote: > >> In-Reply-To: (snip) >>> Of course we users will complain about removals, but we'll knuckle >>> down and take our medicine eventually ;-) >> >> Except that in this case, removal will also complicate code in some >> cases. Consider this fragment of Tkinter logic: >> >> UI.CmdBtn.menu.add_command(label="MyLabel", >> command=lambda cmd=cmdkey: >> CommandMenuSelection(cmd)) >> > > In this case you perhaps should try using a class like so:- > > UI.CmdBtn.menu.add_command(label="MyLabel", > command=CommandMenuSelectionCallback(cmdkey)) > > Where CommandMenuSelectionCallback is a class like so: > > class CommandMenuSelectionCallback: > def __init__(self, key): > self.key = key > > def __call__(self): > print self.key Looks like Java. From janeaustine50 at hotmail.com Sat Mar 12 09:18:27 2005 From: janeaustine50 at hotmail.com (janeaustine50 at hotmail.com) Date: 12 Mar 2005 06:18:27 -0800 Subject: bsddb support for berkeley db 4.3? Message-ID: <1110637107.460383.269730@f14g2000cwb.googlegroups.com> It doesn't seem like the python 2.4(and the recent 2.4.1) support berkeley db 4.3. (4.3 fixes some deadlock bugs I occasionally encounter using 4.2.) bsddb3(at pybsddb.sf.net) already supports 4.3 since last December(but doesn't explicitly support win32 -- see the assert statement in setup.py). I thought the bsddb3 project were merged into the python project. Hasn't it? From steve at holdenweb.com Thu Mar 3 18:43:36 2005 From: steve at holdenweb.com (Steve Holden) Date: Thu, 03 Mar 2005 18:43:36 -0500 Subject: There's GOT to be a better way! In-Reply-To: References: Message-ID: Earl Eiland wrote: > On Thu, 2005-03-03 at 15:11, Steve Holden wrote: > >>Earl Eiland wrote: >> >>>I'm writing my first program where I call custom modules. The 'global' >>>command doesn't seem to apply, so how do I change a variable internally >>>in a module without passing it down n layers, and then back out again? >>> >> >>You are correct in assuming that global isn't what you want - it really >>means "global to the module namespace in which it appears". >> >>However, if two separate pieces of code can both reference the same >>module then one can set an attribute in the module and the other can >>reference it. Don't forget that when you import a module its name >>becomes global within the importing module. Since a module is just a >>glorified namespace, anything that can reference the module can read >>and/or set that module's attributes. >> >>a.py: >> >>import something >>something.x = "A value" >> >>b.py: >> >>import something >>print something.x >> >>will print "A value" as long as a is imported before b. > > Right. That part I figured out. How does one function in an imported > module access a variable in the same module? > > module.py > def A(): global test > test = 1 > for x in range(10): B() > > def B(): global test > test = test + 1 > > > main.py > import module > module.A() print module.test > > > This will fail, unless test is passed and returned. > regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From noway at sorry.com Wed Mar 30 19:34:24 2005 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 31 Mar 2005 00:34:24 GMT Subject: McMillan Installer vs. Python 2.4 References: <1112226695.206011.34200@z14g2000cwz.googlegroups.com> Message-ID: mrmakent at cox.net wrote: > 1. Does anyone know why McMillan Installer 5b5 does not work with > Python 2.4 under Linux (works with Python 2.3 just fine), and how to > fix it? No, sorry. I know for a fact that it does not work out of the box for Windows because of the prebuilt executables (run*.exe) which are compiled with VC6 and must be recompiled with VC7.1. After that, it works for me with Python 2.4. > 2. Will anyone be picking up the maintenance and development ball for > McMillan Installer? I hope someone eventually will. Meanwhile, we got a python24.dll which is 1.8Mb so that the py2exe guys are happy. Sigh. I hope this wasn't done only for the sake of py2exe though: it would be just wrong to hurt everybody for the sake of those installers that can't do a single executable. -- Giovanni Bajo From cam.ac.uk at mh391.invalid Mon Mar 14 13:47:13 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 14 Mar 2005 18:47:13 +0000 Subject: optparse alternative In-Reply-To: References: Message-ID: Henry Ludemann wrote: > I've been writing an optparse alternative (using getopt) that is at a > stage where I'd be interested in people's opinions. Thanks for the work and letting us see it! As far as I can tell, your module has one functional advantage over optparse--it validates arguments as well as options. The rest seems to be cosmetics, and personally I prefer the cosmetics of optparse. For one thing, it uses the variable/function naming style found throughout most of the stdlib. optparse has also been widely used and tested for the last four years. I think you would be better off trying to extend optparse to deal with non-option arguments, and you can tap into the installed base of existing optparse users and even get your code included in the stdlib if Greg Ward agrees. Whereas that's really unlikely for an entirely new module--there just isn't the need for a THIRD way to do the same thing. Just a suggestion. -- Michael Hoffman From wade_stoddard at yahoo.com Sun Mar 6 18:32:31 2005 From: wade_stoddard at yahoo.com (Igorati) Date: Sun, 06 Mar 2005 18:32:31 -0500 Subject: Coding help...very basic References: <68d845a730e35c043ac2dae42b4d40f4@localhost.talkaboutprogramming.com> Message-ID: <5434a51b6bce437fab58318e20443db8@localhost.talkaboutprogramming.com> Thank both for the help. I understand that I should provide code, I am still trying to understand what to do, I don't want the work done, just some ideas of where to go, a general layout perhaps. Thank you. From pinard at iro.umontreal.ca Mon Mar 7 14:38:31 2005 From: pinard at iro.umontreal.ca (=?iso-8859-1?Q?Fran=E7ois?= Pinard) Date: Mon, 7 Mar 2005 14:38:31 -0500 Subject: shuffle the lines of a large file In-Reply-To: <200503071527.15805.modelnine@ceosg.de> References: <1110202592.006137.32560@o13g2000cwo.googlegroups.com> <200503071520.17490.modelnine@ceosg.de> <200503071527.15805.modelnine@ceosg.de> Message-ID: <20050307193831.GB14612@alcyon.progiciels-bpi.ca> [Heiko Wundram] > Replying to oneself is bad, [...] Not necessarily. :-) -- Fran?ois Pinard http://pinard.progiciels-bpi.ca From tom.cocagne at gmail.com Fri Mar 18 19:46:15 2005 From: tom.cocagne at gmail.com (Tom Cocagne) Date: Fri, 18 Mar 2005 19:46:15 -0500 Subject: PyGTK and pyexe References: <1111189688.629652.279790@o13g2000cwo.googlegroups.com> Message-ID: <113mti3b4i3pq87@corp.supernews.com> I used the instructions in the PyGTK FAQ and managed to get it working. Take a look at: http://www.async.com.br/faq/pygtk/index.py?req=show&file=faq21.005.htp Cheers, Rakis Viktor wrote: > Did anybody managed to "pack", a program that uses pygtk with pyexe? > > The best result I got was: > > Pango-ERROR **: file shape.c: line 75 (pango_shape): assertion faled: > (glyphs->num_glyphs > 0) aborting... > > I'm using python2.4, pygtk-2.6.1-1.win32-py2.4, gtk-win32-2.6.4-rc1. > > Thanks in advance. From theller at python.net Sat Mar 12 07:06:40 2005 From: theller at python.net (Thomas Heller) Date: Sat, 12 Mar 2005 13:06:40 +0100 Subject: [Ann] ctypes 0.9.5 released Message-ID: ctypes 0.9.5 released - Mar 11, 2005 ==================================== Overview ctypes is an advanced ffi (Foreign Function Interface) package for Python 2.3 and higher. ctypes allows to call functions exposed from dlls/shared libraries and has extensive facilities to create, access and manipulate simple and complicated C data types in Python - in other words: wrap libraries in pure Python. It is even possible to implement C callback functions in pure Python. ctypes runs on Windows, MacOS X, Linux, Solaris, FreeBSD, OpenBSD. It may also run on other systems, provided that libffi supports this platform. For windows, ctypes contains a ctypes.com package which allows to call and implement custom COM interfaces. Important If you download the source distribution, please choose the ZIP file for Windows, and the .tar.gz file for other machines. These archive have different contents! There have been lots of changes - if you are the author or user of a package that uses ctypes, please test it with this release and report problems on the ctypes-users mailing list. Additions New package ctypes.wrap. This contains decorators usable for easier creation of wrapper functions. This package also contains a toolchain for (semi)automatic creation of wrappers for external libraries - it can parse C header files and generate ctypes code for the declarations in them. It can even handle preprocessor definitions! For details, see http://starship.python.net/crew/theller/ctypes/codegen.html Changes in 0.9.5 On systems where sizeof(int) == sizeof(long), c_int/c_long and c_uint/c_ulong are now aliases. Similar for c_long/c_longlong and c_ulong/c_ulonglong. This prevents unneeded type errors. If an exception occurs in a callback function, a full traceback is now printed. Raising SystemExit in a callback function now correctly exists Python. HRESULT is now a proper ctype - no longer a function. This allows to use it in the argtypes sequence for function prototypes. An easier way to define structures and unions that reference themselves, or have dependencies to other data types. The _fields_ attribute can now be set *after* the Structure/Union class has been created. This makes the SetPointerType function obsolete. The semantics of the _fields_ attribute in sub-subclasses of Structure and Union has been fixed. The baseclasses _fields_ list is extended, not replaced, in subclasses. Assigning _fields_ when it is no longer possible raises an error now. Structures and unions now work as restype and in the argtypes list for functions. An important bug has been fixed with pointers. Detailed changelogs are in CVS: Download Downloads are available in the sourceforge files section Separate source distributions are available for windows and non-windows systems. Please use the .zip file for Windows (it contains the ctypes.com framework), and use the .tar.gz file for non-Windows systems (it contains the complete cross-platform libffi sources). Binary windows installers, which contain compiled extension modules, are also available, be sure to download the correct one for the Python version you are using. Homepage Enjoy, Thomas From nessus at mit.edu Tue Mar 1 13:22:22 2005 From: nessus at mit.edu (Douglas Alan) Date: Tue, 01 Mar 2005 13:22:22 -0500 Subject: yield_all needed in Python References: Message-ID: Duncan Booth writes: > Douglas Alan wrote: >> "Terry Reedy" writes: >>> Cetainly, if >> iterator> == , I don't see how anything >>> is gained except for a few keystrokes. >> What's gained is making one's code more readable and maintainable, >> which is the one of the primary reasons that I use Python. > On of the reasons why Python is readable is that the core language is > comparatively small. It's not that small anymore. What it *is* is relatively conceptually simple and readily comprehensible (i.e. "lightweight"), unlike languages like C++ and Perl. > Adding a new reserved word simply to save a few > characters It's not to "save a few characters". It's to make it immediately clear what is happening. > is a difficult choice, and each case has to be judged on its merits, > but it seems to me that in this case the extra syntax is a burden > that would have to be learned by all Python programmers with very > little benefit. The amount of effort to learn what "yield_all" does compared to the amount of effort to understand generators in general is so miniscule, as to be negligible. Besides, by this argument, the standard library should be kept as small as possible too, since people have to learn all that stuff in order to understand someone else's code. > Remember that many generators will want to do slightly more than just yield > from another iterator, and the for loop allows you to put in additional > processing easily whereas 'yield_all' has very limited application e.g. > for tok in tokenstream(): > if tok.type != COMMENT: > yield tok > I just scanned a random collection of my Python files: out of 50 yield > statements I found only 3 which could be rewritten using yield_all. For me, it's a matter of providing the ability to implement subroutines elegantly within generators. Without yield_all, it is not elegent at all to use subroutines to do some of the yielding, since the calls to the subroutines are complex, verbose statements, rather than simple ones. I vote for the ability to have elegant, readable subroutining, regardless of how much you in particular would use it. |>oug From tjreedy at udel.edu Sun Mar 27 12:39:38 2005 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 27 Mar 2005 12:39:38 -0500 Subject: Python List Issue References: Message-ID: "Nick L" wrote in message news:ADu1e.23161$fn3.19315 at attbi_s01... > I've hit a brick wall on something that I'm guessing is pretty simple but > it's driving me nuts. I noticed that with python lists, generally when > you > make a copy of a list (ie, List1 = List2) Python is not C, etc. Assigning a name to an object *never* makes a copy. Assigning a second name creates an alias. Aliases are problems in any language that allows them (which C does also, via pointers). Consider Nick_PythonLearner = Nick_L > List1 just becomes a reference to List2 Ditto for the two Nick names, but better said, both names refer to the same person (or list). > and any modifications done to List1 affects List2. and ditto for a person with more than one name -- which is almost everyone in the modern world (Nick, Mr. L, etc). > Ok I can live with this Good. Name confusion is everywhere. > but I want to make a completely seperate [sic] copy not attached to the > original in anyway. So then I used this method. List1 = List2[:] For a shallow (one level) copy, List1=list(List2) is now prefered. For a deep (complete, all-level) copy, follow Kern's advice: copy.deepcopy. Terry J. Reedy From bdesth.quelquechose at free.quelquepart.fr Wed Mar 30 15:24:53 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 30 Mar 2005 22:24:53 +0200 Subject: Problem in designing a global directory in python In-Reply-To: <1112124952.537975.129280@f14g2000cwb.googlegroups.com> References: <1112118646.177300.24800@g14g2000cwa.googlegroups.com> <4249a93e$0$26837$626a14ce@news.free.fr> <1112124952.537975.129280@f14g2000cwb.googlegroups.com> Message-ID: <424b076f$0$2857$626a14ce@news.free.fr> Tian a ?crit : > I googled about how to write singleton in python, but even if I use > Singleton, in which module's namespace should I keep the instance of > this singleton? You found the doc but I'm afraid you did not grasp the concept. You don't have to 'keep the instance' anywhere - it's the job of the singleton to do this. The principle of the Singleton is that you can have *only one* instance of it. From engsolnorm at peak.org Thu Mar 3 22:34:59 2005 From: engsolnorm at peak.org (engsol) Date: Thu, 03 Mar 2005 19:34:59 -0800 Subject: How would you program this? References: <0vWdnRNHHMkuVbrfRVn-sg@comcast.com> Message-ID: On Thu, 03 Mar 2005 19:32:19 -0700, Steven Bethard wrote: >engsol wrote: >> I don't fully understand this line of your code: >> return [(a,b,c) for a in ns for b in ns for c in ns if a + b + c == limit] >> If the "if" part is true, does it 'trigger' the return? > >This code is basically equivalent to: > >lc = [] >for a in ns: > for b in ns: > for c in ns: > if a + b + c == limit: > lc.append((a, b, c)) >return lc > >Does that help? > >STeVe Now it's clear....thank you. Norm B From fusionary_2000 at yahoo.com Sat Mar 12 23:08:36 2005 From: fusionary_2000 at yahoo.com (Gensek) Date: 12 Mar 2005 20:08:36 -0800 Subject: Why does this not work? In-Reply-To: References: <1110602822.183262.200800@o13g2000cwo.googlegroups.com> <1110657914.451814.243590@g14g2000cwa.googlegroups.com> <1110682525.153454.80510@f14g2000cwb.googlegroups.com> Message-ID: <1110686916.572287.9790@g14g2000cwa.googlegroups.com> I fixed it already, as I said. The problem had nothing to do with wxPython. I just used my own functions in the wrong way. From peter at engcorp.com Tue Mar 8 10:59:08 2005 From: peter at engcorp.com (Peter Hansen) Date: Tue, 08 Mar 2005 10:59:08 -0500 Subject: looking for way to include many times some .py code from anotherpython code In-Reply-To: References: <422d9b47$1@nntp0.pdx.net> <395ncpF5sl0i3U1@individual.net> Message-ID: Martin MOKREJ? wrote: > Am I so deperately fighting the language? No-one here on the list needs > to set hundreds variables at once somewhere in their code? Nobody needs to do that. As others have pointed out, creating variables implies wanting to access them distinctly, not as a whole group. If you are just going to access them as a group, use contain objects such as lists or dicts or a custom class, not individual variables. > Now have to figure out how to assign them easily into the XML tree. This might be the hint that others were hoping for, about your real requirements. Do you mean to say that the whole reason you have for assigning hundreds of variables is to go and shove the values right back into another data structure such as an XML document? If so, trust us, you very likely don't want to do it by assigning and then referencing hundreds of variables. -Peter From gouqizi.lvcha at gmail.com Sun Mar 13 22:11:52 2005 From: gouqizi.lvcha at gmail.com (gouqizi.lvcha at gmail.com) Date: 13 Mar 2005 19:11:52 -0800 Subject: Convert python to exe In-Reply-To: References: <1110753113.187057.279740@l41g2000cwc.googlegroups.com> Message-ID: <1110769912.028577.154750@l41g2000cwc.googlegroups.com> Thanks. From reinhold-birkenfeld-nospam at wolke7.net Sun Mar 20 05:26:35 2005 From: reinhold-birkenfeld-nospam at wolke7.net (Reinhold Birkenfeld) Date: Sun, 20 Mar 2005 11:26:35 +0100 Subject: Pre-PEP: Dictionary accumulator methods In-Reply-To: <1111271895.425549.291530@l41g2000cwc.googlegroups.com> References: <1111266424.397453.43860@o13g2000cwo.googlegroups.com> <3a3maoF66u3ggU1@individual.net> <1111271895.425549.291530@l41g2000cwc.googlegroups.com> Message-ID: <3a51a6F68qmqgU2@individual.net> John Machin wrote: > Reinhold Birkenfeld wrote: >> John Machin wrote: >> Are you kidding? If you know what "set" and "default" means, you will > be >> able to guess what "setdefault" means. Same goes for updateBy. >> > > No I'm not kidding -- people from some cultures have no difficulty at > all in mentally splitting up "words" like "setdefault" or the German > equivalent of "Danubesteamnavigationcompany'sdirector'swife"; others > from other cultures where agglutinisation is not quite so rife will > have extreme difficulty. Okay - as I'm German I might be preoccupied on this matter Reinhold From nytimes at swiftdsl.com.au Wed Mar 16 05:57:48 2005 From: nytimes at swiftdsl.com.au (news.sydney.pipenetworks.com) Date: Wed, 16 Mar 2005 21:57:48 +1100 Subject: Python becoming less Lisp-like In-Reply-To: <878y4o55dw.fsf@wilson.rwth-aachen.de> References: <543c3153frfgbaear473m2jji40hub538k@4ax.com> <87zmx5n87e.fsf@wilson.rwth-aachen.de> <87vf7tiblj.fsf@wilson.rwth-aachen.de> <5339b60d.0503150321.3365572e@posting.google.com> <87br9lnndx.fsf@wilson.rwth-aachen.de> <4237ABC0.8000502@swiftdsl.com.au> <878y4o55dw.fsf@wilson.rwth-aachen.de> Message-ID: <4238112C.9040505@swiftdsl.com.au> Torsten Bronger wrote: > Hall?chen! > > "news.sydney.pipenetworks.com" writes: > > >>Torsten Bronger wrote: >> >> >>>[...] >>> >>>I have exactly the same impression, but for me it's the reason >>>why I feel uncomfortable with them. For example, I fear that a >>>skilled package writer could create a module with surprising >>>behaviour by using the magic of these constructs. I don't know >>>Python well enough to get more specific, but flexibility almost >>>always make confusing situations for non-hackers possible. >> >>In that case I wouldn't worry about the magic which can be done in >>python but the magic which can be done in C (which many modules >>are written in). > > > The magic in Python must allow the magic in C. > You have answered your own question. >>Sometimes I think people complain just to complain. > > > It's interesting though that the concerns I mentioned have > influenced so many language designs, isn't it? > > Look, you may weight the pros and cons differently from me, that's > perfectly okay. But don't tell me my thoughts were invalid. > I agree. It was an uncalled for statement and I apologise. I guess theres got to be critics for the language to become better. I just think certain arguments are a bit thin. Especially all the talk about the decorator syntax. I have never seen so much discussion over such a small detail. It's not as if the BDFL is going to start introducing all types of special chars in the language. From the way people carry on, it shall as heck sounds like it. More in relation to the original topic, why can't people just ignore features they don't understand and may never use directly. Tell me you understand exactly how every single module you have ever used works whether or not its written in pure simple python or python with hacky features. Regardless of how a piece of software is written, as long as it works, has a good test bed, has a smart programmer behind, then lets trust the guy to do a good job. If you don't, then you can write it yourself which means you can do exactly how you want it which again makes the whole argument mute. You can't take a ride on someones sweat and blood and expect them to control how they program as well can you ? If you're paying them, then make sure they don't use any special features. Huy From aquila.deus at gmail.com Thu Mar 31 09:47:36 2005 From: aquila.deus at gmail.com (Aquila Deus) Date: 31 Mar 2005 06:47:36 -0800 Subject: How To Do It Faster?!? In-Reply-To: References: Message-ID: <1112280456.610878.323340@g14g2000cwa.googlegroups.com> andrea.gavana at agip.it wrote: > Hello NG, > > in my application, I use os.walk() to walk on a BIG directory. I need > to retrieve the files, in each sub-directory, that are owned by a > particular user. Noting that I am on Windows (2000 or XP), this is what I > do: > > for root, dirs, files in os.walk(MyBIGDirectory): > > a = os.popen("dir /q /-c /a-d " + root).read().split() > > # Retrieve all files owners > user = a[18::20] > > # Retrieve all the last modification dates & hours > date = a[15::20] > hours = a[16::20] > > # Retrieve all the filenames > name = a[19::20] > > # Retrieve all the files sizes > size = a[17::20] > > # Loop throu all files owners to see if they belong > # to that particular owner (a string) > for util in user: > if util.find(owner) >= 0: > DO SOME PROCESSING > > Does anyone know if there is a faster way to do this job? You may use "dir /s", which lists everything recursively. From me at privacy.net Sat Mar 19 08:12:14 2005 From: me at privacy.net (Dan Sommers) Date: 19 Mar 2005 08:12:14 -0500 Subject: Pre-PEP: Dictionary accumulator methods References: Message-ID: On Sat, 19 Mar 2005 01:24:57 GMT, "Raymond Hettinger" wrote: > The proposed names could possibly be improved (perhaps tally() is more > active and clear than count()). Curious that in this lengthy discussion, a method name of "accumulate" never came up. I'm not sure how to separate the two cases (accumulating scalars vs. accumulating a list), though. Regards, Dan -- Dan Sommers ?? ? ?? ? c? = 1 From maxm at mxm.dk Tue Mar 8 07:09:07 2005 From: maxm at mxm.dk (Max M) Date: Tue, 08 Mar 2005 13:09:07 +0100 Subject: Best way to make a list unique? In-Reply-To: References: <1109846699.230667.94850@o13g2000cwo.googlegroups.com> <1109952406.100434.92230@l41g2000cwc.googlegroups.com> <4228b36f$1_1@newspeer2.tds.net> Message-ID: <422d95be$0$236$edfadb0f@dread12.news.tele.dk> Eric Pederson wrote: > I have > > >>>>listA=[1,2,3,4,5,4,3,4,3,2,1] > > > and I want a list of only the unique members. > > This seems inefficient, but works fine over my small sample lists: > > >>>>listA=[a for a in set(listA)] > > Is there a more efficient approach for cases where listA is large? no. Even though the code can be a little simpler: listA = list(Set(listA)) You don't even need to convert it to a list. You can just iterate over the set. >>> la = [1,2,3,4,3,2,3,4,5] >>> from sets import Set >>> sa = Set(la) >>> for itm in sa: ... print itm 1 2 3 4 5 -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From alexrait at gmail.com Wed Mar 9 04:40:05 2005 From: alexrait at gmail.com (alexrait1) Date: 9 Mar 2005 01:40:05 -0800 Subject: popen2.Popen3 doesn't work well for me Message-ID: <1110361205.485173.159630@o13g2000cwo.googlegroups.com> I launch my python. Then I write this: import popen2 popen2.Popen3("mplayer *.mpg") it starts playing for 2 seconds.. and then stops... if I quit python (ctrl - D) mplayer continues to run and plays music as it should... Any ideas? From dima at trit.invalid Tue Mar 1 00:49:34 2005 From: dima at trit.invalid (Dima Dorfman) Date: 1 Mar 2005 05:49:34 GMT Subject: zlib.decompress cannot, gunzip can References: <1109638396.839493.50070@l41g2000cwc.googlegroups.com> Message-ID: On 2005-03-01, enrio at online.no wrote: > I have a string which I try to decompress: > > body = zlib.decompress(body) > > but I get > > zlib.error: Error -3 while decompressing data: incorrect header check > > However, I can write the string to a file and run gunzip with the > expected results: gzip files have a header preceding the zlib stream. Try the gzip module. From olczyk2002 at yahoo.com Tue Mar 22 11:02:35 2005 From: olczyk2002 at yahoo.com (TLOlczyk) Date: Tue, 22 Mar 2005 10:02:35 -0600 Subject: compiled open source Windows lisp (was Re: Python becoming less Lisp-like) References: <543c3153frfgbaear473m2jji40hub538k@4ax.com> <39ofp6F64ap3nU1@individual.net> <39oukjF4bk3ceU1@individual.net> Message-ID: <4ve041p3ik8k98f282lgtrk8k7k7ojh6bc@4ax.com> On 16 Mar 2005 06:37:45 -0500, Carl Shapiro wrote: >I have a virtually completed port of CMUCL to Win32. And, if I was >not busy organizing a Lisp conference, it would be publicly available >by now. If it's the conference I think, then the deadline for papers was about a week ago. I suspect that most of the other routine parts have been taken care of leaving scheduling. IOW your time is freeing up. OTOH it may just be wishful thinking on my part. Any idea how much longer? The reply-to email address is olczyk2002 at yahoo.com. This is an address I ignore. To reply via email, remove 2002 and change yahoo to interaccess, ** Thaddeus L. Olczyk, PhD There is a difference between *thinking* you know something, and *knowing* you know something. From apardon at forel.vub.ac.be Tue Mar 29 07:53:05 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 Mar 2005 12:53:05 GMT Subject: Queue.Queue-like class without the busy-wait References: <1111707620.556818.289300@g14g2000cwa.googlegroups.com> <7xmzsshzxr.fsf@ruckus.brouhaha.com> <7x8y4cyr70.fsf@ruckus.brouhaha.com> <7xoed86lnd.fsf@ruckus.brouhaha.com> <7xfyyjcu5w.fsf@ruckus.brouhaha.com> <7xsm2e7kg7.fsf@ruckus.brouhaha.com> <7xvf7aws6c.fsf@ruckus.brouhaha.com> Message-ID: Op 2005-03-29, Paul Rubin schreef : > Antoon Pardon writes: >> I'm not going to call my solution simple, but it wastes very few >> cycles. if no thread is blocked on a lock, the select will just >> block until that changes. No need for some kind of polling loop. > > I think I understand. My original idea was to use a heapq to be able > to know exactly when the next pending timeout is due, and usleep for > long enough to wake up at just the right time. Then you service the > timeout, pop the heap to find when the next timeout after that is, and > usleep again. No polling loops and no pipe. But it could be that > someone inserts a new timeout while you're sleeping, that's due before > you're scheduled to wake up. Your pipe scheme takes care of that, > since any thread can write to the pipe and wake up the blocked thread > at any time. Right, that is the idea. > Really, the culprit here is the weak signalling scheme in Python. > There needs to be a way to send signals to threads, or raise > asynchronous exceptions in them. There's been some discussion in > sourceforge about that, but the issues involved are complex. Well I have raised this issue before and as far as I understand, the big problem seems to be the various kind of behaviour you can get depending on what platform you are working, so writing a module so that python programs behave the same on various platforms seems a hell of a job. So I decided not to pester the python people for this kind of functionality, although I would very much like to have it. I have been playing with the C-API and have somekind of class that allows one thread to raise an excetion in an other but that wouldn't be a solution here, since the raised exception will not manifest itself while the thread is in a C-function. > I think the best bet for the short term is handling it at the C level, > with sigalarm. Another way is to have chained sigalarm handlers in > the main thread. Possible, but I don't have the time to investigate that possibility now. -- Antoon Pardon From smadim2 at grads.ece.mcmaster.ca Wed Mar 2 16:43:29 2005 From: smadim2 at grads.ece.mcmaster.ca (M.N.A.Smadi) Date: Wed, 02 Mar 2005 16:43:29 -0500 Subject: substring matching Message-ID: <42263381.8060507@grads.ece.mcmaster.ca> hi; say i have the following variable data="""XYZ dflsjdfkl sdfsdhfl jdsflkdsjf sldjfsldjf """ i need to make sure that the first part is actually XYZ, is there an easy way of doing that? thanks m.smadi From timr at probo.com Fri Mar 18 01:02:48 2005 From: timr at probo.com (Tim Roberts) Date: Thu, 17 Mar 2005 22:02:48 -0800 Subject: Is Python like VB? References: <39sj7hF62s0etU1@individual.net> Message-ID: "Mike Cox" wrote: > >As you may or may not know, Microsoft is discontinuing Visual Basic in favor >of VB.NET and that means I need to find a new easy programming language. I >heard that Python is an interpreted language similar to VB. This statement is a little bit silly. VB.NET is an interpreted language which is practically indistinguishable from the old VB. Why on earth would you choose to reimplement your software in a different language, rather than just do the simple version upgrade? >Where I work we use Microsoft Office with a lot of customization using >Visual Basic. The VB in Microsoft Office is not being discontinued. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at holdenweb.com Wed Mar 9 05:12:41 2005 From: steve at holdenweb.com (Steve Holden) Date: Wed, 09 Mar 2005 05:12:41 -0500 Subject: popen2.Popen3 doesn't work well for me In-Reply-To: <1110361205.485173.159630@o13g2000cwo.googlegroups.com> References: <1110361205.485173.159630@o13g2000cwo.googlegroups.com> Message-ID: alexrait1 wrote: > I launch my python. Then I write this: > import popen2 > popen2.Popen3("mplayer *.mpg") > > it starts playing for 2 seconds.. and then stops... > if I quit python (ctrl - D) > mplayer continues to run and plays music as it should... > > Any ideas? > It looks like the process you start is blocking on standard input or output. Does os.system("mplayer *.mpg") do what you want? regards Steve From nbbalane at gmail.com Thu Mar 31 05:01:14 2005 From: nbbalane at gmail.com (jrlen balane) Date: Thu, 31 Mar 2005 18:01:14 +0800 Subject: is there a problem on this simple code In-Reply-To: <2cad2090050330133919f1fdf7@mail.gmail.com> References: <2cad2090050315012623f960ac@mail.gmail.com> <1110881620.211571.73240@o13g2000cwo.googlegroups.com> <2cad209005031515345021d9a6@mail.gmail.com> <2cad2090050315163370237944@mail.gmail.com> <8uif311tdouiromsjp0que1mbnsc9ssoe7@4ax.com> <2cad2090050330133919f1fdf7@mail.gmail.com> Message-ID: <2cad20900503310201629bc3af@mail.gmail.com> hi! could anyone give their input on my previous post about timer and threading...] pleaseee... my program seemed to just run first the thread then when it encounters error on the thread that's the time that other part of the program got the chance to be executed even the timer even is not executed while the thread is running On Thu, 31 Mar 2005 05:39:11 +0800, jrlen balane wrote: > a simple question regarding threading and timer: > > if i put my timer control inside the thread, will the thread be exited > every time there is a timer event??? > > please help... > > def someThreadHere() > ... > someTimer.start(3000) > .... > > def someTimerEvent() > ..... > > On Wed, 16 Mar 2005 07:38:09 GMT, Dennis Lee Bieber > wrote: > > On Wed, 16 Mar 2005 09:47:01 +0800, jrlen balane > > declaimed the following in comp.lang.python: > > > > > please post your suggestions? please ... > > > > > Since we don't have your hardware, nor have you been able supply > > the formal documentation of the protocol in use, all we can do is > > comment on coding styles and obvious errors in the code... If there is > > an flaw in the implementation of the protocol, we have no way to tell. > > > > > > > > > > > import sys > > > > import serial > > > > import sys, os > > > > import serial > > > > How about cleaning that up... You've imported serial twice, and > > sys twice. > > > > > > data_file = open('C:/Documents and Settings/nyer/Desktop/IRRADIANCE.txt', 'r') > > > > data = data_file.readlines() > > > > > > > > def process(list_of_lines): > > > > data_points = [] > > > > for line in list_of_lines: > > > > data_points.append(int(line)) > > > > return data_points > > > > > > > > irradiance = process(data) > > > > Well, this is legal, though confusing to stuff a function > > definition between lines of the main program. Common is to put the > > "def"s after the "imports" (though defining "constants" may be okay in > > there) > > > > If "process" is only used once, it might not even be worth the > > "def"... > > > > > > > > > > ser = serial.Serial() > > > > ser.baudrate = 9600 > > > > ser.port = 0 > > > > ser > > Delete that -- you've been told that it is meaningless for days > > now... If you don't want to take advice, why ask? > > > > > > > > > > ser.open() > > > > tx_command = 67 > > > > tx_no_databyte = 2 > > > > tx_message_no = 1 > > > > tx_len = len (irradiance) > > > > > > > > for j in range (tx_len) : > > > > start_time = time.time() > > > > > > > > temp1 = [] > > > > temp2 = [] > > > > pyra1 = [] > > > > pyra2 = [] > > > > voltage = [] > > > > current = [] > > > > > > > > current_time = time.time() > > > > > > > > while( current_time >= start_time + 300): > > > > > > If current time is < start+300, the entire loop will be skipped > > -- a condition that is quite likely to happen unless you have a /very/ > > slow machine. > > > > > > data_hi, data_lo = divmod(irradiance[j], 0x100) > > > > tx_checksum = -(data_hi + data_lo + tx_command + tx_message_no > > > > + tx_no_databyte) & 0xff > > > > ser.write(pack('6B', tx_command, tx_message_no, > > > > tx_no_databyte, data_lo, data_hi, tx_checksum)) > > > > > > > > rx_data = ser.read(19) > > > > rx_len = len(rx_data) > > > > byte = [ord(x) for x in rx_data] > > > > > > > > if rx_len < 10: > > > > #print 'it is not pumping data out as fast as we assumed' > > > > sys.exit(1) > > > > > > > > for k in range (rx_len-9): > > > > if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) > > > > & 0xff == 0: > > > > #print byte[k:k+10] > > > > > > > > temp1.append(byte[k+3]) > > > > temp2.append(byte[k+4]) > > > > pyra1.append(byte[k+5]) > > > > pyra2.append(byte[k+6]) > > > > voltage.append(byte[k+7]) > > > > current.append(byte[k+8]) > > > > print temp1, temp2, pyra1, pyra2, voltage, current > > > > > > All these are lists, do you really mean to print the entire list > > each time, or only the most recent data value? > > > > > > current_time = time.time() > > > > > > > > while theres no error in the output, there is also no response from > > > > the hardware or maybe communication is off. > > > > > > > > could somebody out there help me. > > > > > > > > > > by the way, here is a working code: though here the data to be > > > > transmitted is just incrementing and not read from a text file: > > > > > > > > import serial > > > > import string > > > > import time > > > > from struct import * > > > > import os > > > > > > > > ser = serial.Serial() > > > > > > > > ser.baudrate = 9600 > > > > ser.port = 0 > > > > ser.timeout = 1 > > > > ser > > > > > > > > ser.open() > > > > tx_command = 67 > > > > tx_message_no = 1 > > > > tx_no_databyte = 2 > > > > item=10000 > > > > for item in range(10000, 30001, 10): > > > > > > > > data_hi, data_lo = divmod(item, 0x100) > > > > tx_checksum = -(data_hi + data_lo + tx_command + tx_message_no + > > > > tx_no_databyte) & 0xff > > > > ser.write(pack('6B', tx_command, tx_message_no, tx_no_databyte, > > > > data_lo, data_hi, tx_checksum)) > > > > #print tx_command, tx_message_no, tx_total_data, data_lo, data_hi, > > > > tx_checksum > > > > > > > > > > > > rx_data = ser.read(19) > > > > rx_len = len(rx_data) > > > > #print 'rx_len', rx_len > > > > byte = [ord(x) for x in rx_data] > > > > #print 'received', byte > > > > > > > > if rx_len < 10: > > > > print 'it is not pumping data out as fast as we assumed' > > > > sys.exit(1) > > > > > > > > for k in range (rx_len-9): > > > > if byte[k] == 70 and byte [k+2] == 6 and sum(byte[k:k+10]) & 0xff == 0: > > > > print byte[k:k+10] > > > > =================================== > > > > outputs: > > > > [70, 2, 6, 54, 197, 253, 230, 231, 211, 26] > > > > [70, 3, 6, 54, 197, 253, 230, 231, 211, 25] > > > > [70, 3, 6, 54, 197, 253, 230, 231, 210, 26] > > > > [70, 3, 6, 54, 197, 253, 230, 231, 210, 26] > > > > [70, 3, 6, 54, 197, 253, 230, 231, 211, 25] > > > > [70, 3, 6, 54, 197, 253, 230, 231, 210, 26] > > > > [70, 3, 6, 54, 197, 253, 230, 231, 211, 25] > > > > [70, 3, 6, 54, 197, 253, 230, 231, 210, 26] > > > > [70, 3, 6, 54, 197, 253, 230, 231, 211, 25] > > > > ... > > > > ... > > > > > > > > And please trim... You don't need to quote the same text over > > and over... We've all seen it by now, or can retrieve it using the > > message headers. > > > > -=-=-=-=-=-=-=-=-=-=-=-=- > > """ > > EVERYTHING THAT FOLLOWS IS THE RESULT OF "FREE ASSOCIATION" > > THINKING. NONE OF IT HAS BEEN TESTED FOR CORRECTNESS OF > > SYNTAX OR SEMANTICS -- IT SHOULD BEST BE CONSIDERED PSEUDO- > > CODE, GIVING A GUIDELINE FROM WHICH TO PROCEED WITH REAL > > DEVELOPMENT > > """ > > > > import serial #I don't have this, and don't have your hardware, > > #so this is all guesswork, and untested > > import os > > import sys > > import time > > import threading > > import Queue > > > > DATA_FID = r"C:\\Documents and Settings\\nyer\\Desktop\\IRRADIANCE.txt" > > #I definitely don't have a "nyer" user > > > > class DeviceHandler(object): > > def _checksum(packet): > > # compute checksum from packet (which should be a list) > > return -sum(packet) & 0xFF > > > > def _Reader(self): > > # worker code for the reader /thread/, continuous > > # loop, reading response packets and putting them > > # (or some error message string) onto the queue > > while 1: > > # accept first three as response code, message count > > # and data length > > response = ord(self._ser.read(1)) > > count = ord(self._ser.read(1)) > > length = ord(self._ser.read(1)) > > # get the data bytes > > data = [] > > for x in range(length): > > data.append(ord(self._ser.read(1))) > > # get the message checksum > > check = ord(self._ser.read(1)) > > # format it all as a packet list > > packet = [response, count, length] + data > > packet = packet.append(check) > > # check for out of sequence packet > > if count != self._RX_count: > > # notify via queue, then reset expected counter > > self._queue.put("Receive packet number is out of > > sequence") > > self._RX_count = count > > # confirm checksome and notify if needed > > if _checksum(packet) != 0: > > self._queue.put("Receive packet checksum is invalid") > > # put the packet, regardless of validity, onto queu > > self._queue.put(packet) > > self._RX_count += 1 & 0xFF #quick & dirty modulo 256 > > > > def __init__(self, port, rate, queue): > > # initialize handler instance > > self._TX_count = 0 > > self._RX_count = 0 > > self._ser = serial.Serial() > > self._ser.port = port > > self._ser.baudrate = rate > > self._ser.open() > > self._queue = queue > > self._reader = threading.Thread(target=self._Reader()) > > # make the reading thread a daemon, so it won't block > > # main program from exiting > > self._reader.setDaemon(True) > > self._reader.start() > > > > def close(self): > > self.ser.close() > > > > def sendPacket(self, Command=0x00, Data = None): > > # format a packet list from input data > > packet = [Command, self._TX_count, len(Data)] + Data > > # append checksum > > packet.append(self._checksum(packet)) > > # convert to string format -- all data better be > > # 0x00 - 0xFF > > output = "".join([chr(x) for x in packet]) > > self._ser.write(output) > > # increment output counter > > self._TX_count += 1 & 0xFF > > > > # MAIN PROGRAM STARTS HERE > > fdata = open(DATA_FID, "r") > > > > # create response transfer queue, and serial port handler instance > > myQ = Queue.Queue() > > myDevice = DeviceHandler(port = 0, rate = 9600, queue = myQ) > > > > for ln in fdata: > > # NOTE: no TIMING of command output is performed, they > > # go out as fast as the response queue can be emptied > > # reset response data array > > temp1 = [] > > temp2 = [] > > pyra1 = [] > > pyra2 = [] > > voltage = [] > > current = [] > > > > # extract all responses that have been received up to now > > # note: this is NOT a loop until empty, only for whatever > > # was available at the start of this pass > > for i in range(myQ.qsize()): > > resp = myQ.get_nowait() > > if type(resp) is types.StringType: > > print "Bad response packet: %s" % resp > > elif resp[2] != 6 or resp[0] != 0x70: > > print "Unexpected response:" > > print " Code = %s\tCount = %s\tLength = %s" % (resp[0], > > resp[1], > > resp[2]) > > print " Data = ", > > for j in range(resp[2]): > > print resp[j + 3], > > print "\tChecksum = %s" % resp[resp[2] +3] > > else: > > # capture data field > > temp1.append(resp[3]) > > temp2.append(resp[4]) > > pyra1.append(resp[5]) > > pyra2.append(resp[6]) > > voltage.append(resp[7]) > > current.append(resp[8]) > > # display current data > > print "Code = %s\tcount = %s\tLength = %s" % (resp[0], > > resp[1], > > resp[2]) > > print "temp1 = %s\ttemp2 = %s" % (resp[3], resp[4]) > > print "pyra1 = %s\tpyra2 = %s" % (resp[5], resp[6]) > > print "voltage = %s\tcurrent = %s" % (resp[7], resp[8]) > > print "\tchecksum = %s" % resp[9] > > > > # process one input data value > > dvalue = int(ln) > > (d_high, d_low) = divmod(dvalue, 0x100) > > > > # send the packet > > myDevice.sendPacket(Command = 0x67, Data = [d_high, d_low]) > > > > #what do you want to do with the arrays that built up, as they get > > #reset on the next loop pass > > print "temp1", temp1 > > print "temp2", temp2 > > print "pyra1", pyra1 > > print "pyra2", pyra2 > > print "voltage", voltage > > print "current", current > > > > # end of input file, close file and exit > > # NOTE: does not wait for response data to catch up > > fdata.close() > > myDevice.close() > > > > -=-=-=-=-=-=-=-=-=-=- > > > > Explore that and see if you can understand the modularization > > (minimal) and processing logic. > > > > -- > > > ============================================================== < > > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > > wulfraed at dm.net | Bestiaria Support Staff < > > > ============================================================== < > > > Home Page: < > > > Overflow Page: < > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From cam.ac.uk at mh391.invalid Mon Mar 7 09:39:03 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 07 Mar 2005 14:39:03 +0000 Subject: Possible to import a module whose name is contained in a variable? In-Reply-To: References: <392dr8F5sqgo1U1@individual.net> <392mgoF5nj49fU1@individual.net> Message-ID: Ed Leafe wrote: > > Is there any way to use __import__ to replace the following: > > exec("from %s import *" % modulename) I shouldn't do this but: module = __import__(modulename) try: for key in module.__all__: globals()[key] = module[key] except AttributeError: globals().update(module.__dict__) But really, you shouldn't be using from x import * as it has unpredictable results as well. http://www.python.org/doc/faq/programming.html#what-are-the-best-practices-for-using-import-in-a-module -- Michael Hoffman From mahs at telcopartners.com Sun Mar 27 21:06:27 2005 From: mahs at telcopartners.com (Michael Spencer) Date: Sun, 27 Mar 2005 18:06:27 -0800 Subject: String Splitter Brain Teaser In-Reply-To: <42475CB7.2030407@po-box.mcgill.ca> References: <200503271439.06181.jstroud@mbi.ucla.edu> <42475CB7.2030407@po-box.mcgill.ca> Message-ID: Brian van den Broek wrote: > > Much nicer than mine. =| :-) > > ^ > | > ---- (hats off) > Cool ascii art (but thanks for the translation)! Michael From steven.bethard at gmail.com Tue Mar 1 15:51:44 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 01 Mar 2005 13:51:44 -0700 Subject: Is it possible to specify the size of list at construction? In-Reply-To: References: <20050301203353.49598.qmail@web54505.mail.yahoo.com> Message-ID: Michael Spencer wrote: > Anthony Liu wrote: > >> I cannot figure out how to specify a list of a >> particular size. >> >> For example, I want to construct a list of size 10, >> how do I do this? >> > A list does not have a fixed size (as you probably know) > > But you can initialize it with 10 somethings > > > >>> [None]*10 > [None, None, None, None, None, None, None, None, None, None] > >>> range(10) > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > >>> Also, list comprehensions may be useful if you have mutable objects: [{} for _ in range(10)] And to see why [{}]*10 is probably not what you want: py> lst = [{}]*10 py> lst[0][1] = 2 py> lst [{1: 2}, {1: 2}, {1: 2}, {1: 2}, {1: 2}, {1: 2}, {1: 2}, {1: 2}, {1: 2}, {1: 2}] py> lst = [{} for _ in range(10)] py> lst[0][1] = 2 py> lst [{1: 2}, {}, {}, {}, {}, {}, {}, {}, {}, {}] STeVe From contact at alanlittle.org Mon Mar 7 05:14:42 2005 From: contact at alanlittle.org (contact at alanlittle.org) Date: 7 Mar 2005 02:14:42 -0800 Subject: mxDateTime on Mac: Fatal Python Error Message-ID: <1110190482.463739.19110@o13g2000cwo.googlegroups.com> I'm trying to get mxDateTime working on a Mac so that I can use pyscopg and cx_Oracle. The Egenix base package builds and installs quite happily, but then when I try to import it I get >> import mx.DateTime Fatal Python error: Interpreter not initialized (version mismatch?) Abort ... any ideas? Environment: OS X 10.3.8 sys.version: '2.3 (#1, Sep 13 2003, 00:49:11) \n[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)]' egenix-mx-base-2.0.6 From smadim2 at grads.ece.mcmaster.ca Wed Mar 9 13:06:46 2005 From: smadim2 at grads.ece.mcmaster.ca (M.N.A.Smadi) Date: Wed, 09 Mar 2005 13:06:46 -0500 Subject: running programs from within python In-Reply-To: References: <422F2982.1030809@grads.ece.mcmaster.ca> Message-ID: <422F3B36.6060701@grads.ece.mcmaster.ca> this is the full error Traceback (most recent call last): File "./plugin.py", line 60, in ? main() File "./plugin.py", line 40, in main os.system("/root/tmp/bibutils_3.14/isi2xml " + isi_file + " > tmp_isi_xml.xml") NameError: global name 'os' is not defined smadi Steven Bethard wrote: > M.N.A.Smadi wrote: > >> am getting an error in the script as follows: >> >> NameError: global name 'os' is not defined >> >> however i dont get the same error when running from the python CLI. >> (and yes i am importing the os module) > > > Can you give the full exception message (i.e. copy-paste it from the > output)? > > STeVe From ville at spammers.com Thu Mar 24 01:57:11 2005 From: ville at spammers.com (Ville Vainio) Date: 24 Mar 2005 08:57:11 +0200 Subject: IronPython 0.7 released! References: <1111603770.909447.18070@z14g2000cwz.googlegroups.com> <4241ea6e$0$11679$8fcfb975@news.wanadoo.fr> <4241F54E.9090101@jessikat.fsnet.co.uk> <42420005.10807@jessikat.fsnet.co.uk> Message-ID: >>>>> "Robin" == Robin Becker writes: Robin> well that's nice, but I don't do blogs and certainly don't You don't need to "do" much - just go to planetpython.org -- Ville Vainio http://tinyurl.com/2prnb From modelnine at ceosg.de Tue Mar 29 21:36:05 2005 From: modelnine at ceosg.de (Heiko Wundram) Date: Wed, 30 Mar 2005 04:36:05 +0200 Subject: How to use "__new__"? In-Reply-To: <311b5ce105032917276a188c59@mail.gmail.com> References: <311b5ce105032917276a188c59@mail.gmail.com> Message-ID: <200503300436.11076.modelnine@ceosg.de> Am Mittwoch, 30. M?rz 2005 03:27 schrieb could ildg: > Thank you. > I'm clear after I read the doc: > If __new__() returns an instance of cls, then the new instance's > __init__() method will be invoked like "__init__(self[, ...])", where > self is the new instance and the remaining arguments are the same as > were passed to __new__(). > > If __new__() does not return an instance of cls, then the new > instance's __init__() method will not be invoked. > > __new__() is intended mainly to allow subclasses of immutable types > (like int, str, or tuple) to customize instance creation. Remember that __new__() can also be used to create singletons (to return a pre-existing instance in case some form of argument matches, for example): class Singleton(object): __buffer = {} def __new__(cls,somearg): if somearg not in cls.__buffer: cls.__buffer[somearg] = super(cls,Singleton).__new__(cls) return cls.__buffer[somearg] def __init__(self,somearg): self.__somearg = somearg def __repr__(self): return "" % (self.__somearg,hex(id(self))) >>> x = Singleton(1) >>> y = Singleton(2) >>> z = Singleton(1) >>> print x >>> print y >>> print z >>> x is y False >>> x is z True >>> y is z False You could extend the above example quite easily to deal with deallocation (a reference to each created singleton is retained using the above class, always, as long as the program is running) and also to make it threadsafe or to disable initialization in case the singleton has already been initialized before. -- --- Heiko. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From deetsNOSPAM at web.de Sun Mar 13 10:25:44 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 13 Mar 2005 16:25:44 +0100 Subject: Extending and Embedding References: Message-ID: Eduardo Rodrigues wrote: > How can I load a module (written in C as a shared > library (.so)) through "PyRun_SimpleString"? > > I've tried "from import *", but a got a > message: ImportError: No module named You can't do this. You have to either wrap the module - which is possible in several ways, including hand-written code, pyrex, swig and sip. Maybe even more, I don't know. Or you access it using the module ctypes that allows to invoke arbitrary methods/funtctions of C-libs. google for it. -- Regards, Diez B. Roggisch From max at alcyone.com Wed Mar 30 23:34:31 2005 From: max at alcyone.com (Erik Max Francis) Date: Wed, 30 Mar 2005 20:34:31 -0800 Subject: return the last item in a list In-Reply-To: References: Message-ID: Raymond Hettinger wrote: >> I'm looking for an 'easy' way to have the last item in a list returned. > > Try mylist.pop() or mylist[-1]. Note that list.pop also removes the last element from the list in the process. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Granted that I must die, how shall I live? -- Michael Novak From jepler at unpythonic.net Mon Mar 21 11:44:50 2005 From: jepler at unpythonic.net (Jeff Epler) Date: Mon, 21 Mar 2005 10:44:50 -0600 Subject: spaces in re.compile() In-Reply-To: References: Message-ID: <20050321164448.GI2168@unpythonic.net> Maybe you want r'\b'. From 'pydoc sre': \b Matches the empty string, but only at the start or end of a word. import re r = re.compile( r'\btest\b' ) print r.findall("testy") print r.findall(" testy ") print r.findall(" test ") print r.findall("test") -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From harlinseritt at yahoo.com Sun Mar 6 16:08:23 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 6 Mar 2005 13:08:23 -0800 Subject: seeking tree-browser widget for use with Tkinter In-Reply-To: References: Message-ID: <1110143303.291783.318180@o13g2000cwo.googlegroups.com> Actually it should be here: http://py.vaults.ca/apyllo.py/808292924.247038364.90387689.96972321 Cheers, Harlin From yatima_ at konishi.polis.net Thu Mar 3 16:40:19 2005 From: yatima_ at konishi.polis.net (Yatima) Date: Thu, 03 Mar 2005 21:40:19 GMT Subject: Multiline regex help References: <4226fc71$1_3@newspeer2.tds.net> <42277d80$1_3@newspeer2.tds.net> Message-ID: <7vLVd.8905$OU1.1568@newssvr21.news.prodigy.com> On Thu, 03 Mar 2005 16:25:39 -0500, Kent Johnson wrote: > Here is another attempt. I'm still not sure I understand what form you want the data in. I made a > dict -> dict -> list structure so if you lookup e.g. scores['10/11/04']['60'] you get a list of all > the RelevantInfo2 values for Relevant1='10/11/04' and Relevant2='60'. > > The parser is a simple-minded state machine that will misbehave if the input does not have entries > in the order Relevant1, Relevant2, Relevant3 (with as many intervening lines as you like). > > All three values are available when Relevant3 is detected so you could do something else with them > if you want. > > HTH > Kent > > import cStringIO > > raw_data = '''Gibberish > 53 > MoreGarbage [mass snippage] > 60 > Lalala''' > raw_data = cStringIO.StringIO(raw_data) > > scores = {} > info1 = info2 = info3 = None > > for line in raw_data: > if line.startswith('RelevantInfo1'): > info1 = raw_data.next().strip() > elif line.startswith('RelevantInfo2'): > info2 = raw_data.next().strip() > elif line.startswith('RelevantInfo3'): > info3 = raw_data.next().strip() > scores.setdefault(info1, {}).setdefault(info3, []).append(info2) > info1 = info2 = info3 = None > > print scores > print scores['10/11/04']['60'] > print scores['10/10/04']['23'] > > ## prints: > {'10/10/04': {'44': ['33'], '23': ['22', '22']}, '10/11/04': {'60': ['45']}} > ['45'] > ['22', '22'] Thank you so much. Your solution and Steve's both give me what I'm looking for. I appreciate both of your incredibly quick replies! Take care. -- You worry too much about your job. Stop it. You are not paid enough to worry. From belred at gmail.com Mon Mar 28 23:13:55 2005 From: belred at gmail.com (Bryan) Date: Mon, 28 Mar 2005 20:13:55 -0800 Subject: collaborative text editor Message-ID: at pycon, several mac users were using a collaborative text editor where each user's text background color was a different color as they edited the same document at the same time while they took notes during the lectures. does anyone know the name of that program? it was one of the coolest things i've ever seen :) thanks, bryan From sc0rp at hot.pl Sun Mar 20 17:43:24 2005 From: sc0rp at hot.pl (Jacek Trzmiel) Date: Sun, 20 Mar 2005 23:43:24 +0100 Subject: simultaneous copy to multiple media References: <3a52b3F66fideU1@individual.net> <3a5ihoF66l2n4U1@individual.net> Message-ID: <423DFC8C.EFCB4361@hot.pl> Claudio Grondi wrote: > I am on a Widows 2000 box using the NTFS file system. > Both up to now suggested approaches as > - tee.exe (where I used the http://david.tribble.com/dos/tee.exe > DOS-port with redirecting stdout to NULL) and > - parallel copy (hoping caching does the job) are by far > slower than the consecutive copy: > single copy speed 12-15 MByte/s > which gives effectively > 6-7 MByte/s, > tee.exe or twice copy in parallel > 1-3 MByte/s. > > Any other suggestions except writing an own > optimised version of tee.exe Try this: http://mastermind.com.pl/multicopy/ This is small tool I've wrote, that does use large memory buffers with asynchronous I/O to copy file. Following command: multicopy c:\testfile d:\testfile e:\testfile f:\testfile will copy c:\testfile to d, e and f disks. With four separate IDE disks I can copy file at about 30MB/s, which means 120MB/s total I/O. You can give it a try, but I don't know if it will work fast with USB drives. HTH, sc0rp. From jstroud at mbi.ucla.edu Tue Mar 29 14:33:03 2005 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 29 Mar 2005 11:33:03 -0800 Subject: Who Knows of a Good Computational Physics Textbook? In-Reply-To: <1110770857.869645.47890@o13g2000cwo.googlegroups.com> References: <1110770857.869645.47890@o13g2000cwo.googlegroups.com> Message-ID: <200503291133.03334.jstroud@mbi.ucla.edu> Look into "Game Physics" by Eberly (Elsevier). On Sunday 13 March 2005 07:27 pm, beliavsky at aol.com wrote: > There is some info on teaching computational physics at Rubin Landau's > site http://www.physics.orst.edu/~rubin/ . > > Springer recently published the book "Python Scripting for > Computational Science" by Hans P. Langtangen . > > Searching "computational physics" at Amazon returns some relevant > books. -- James Stroud, Ph.D. UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From aprakash at visolve.com Thu Mar 31 06:59:55 2005 From: aprakash at visolve.com (Prakash A) Date: Thu, 31 Mar 2005 17:29:55 +0530 Subject: no module named fcntl Message-ID: <032001c535e9$28b30480$1a0110ac@PRACO> Hello All, I new user to python. I am using a product called FSH, some of its parts are implemented in Python. This is like a ssh to run a command on remote machine. First time while running the fsh there was on. # fshd Traceback (most recent call last): File "/usr/bin/in.fshd", line 6, in ? import infshd File "/home/pra/fsh/1.2/Fileset/share/fsh/infshd.py", line 19, in ? import fcntl ImportError: No module named fcntl I solved this problem. This error is because, fcntl.sl is unable load and the user has no permission to execute the library. After changing the permission for the shared library, it works. But again the problem arises after some time, with out no change. This time # fshd -l user localhost user at localhost password: Traceback (most recent call last): File "/usr/bin/in.fshd", line 6, in ? import infshd File "/home/pra/fsh/1.2/Fileset/share/fsh/infshd.py", line 19, in ? import fcntl ImportError: No module named fcntl Pls. suggest me any solution. Pls. forgive me if it is already discussed. Thanks & Reagrds Prakash.A -------------- next part -------------- An HTML attachment was scrubbed... URL: From deetsNOSPAM at web.de Fri Mar 11 08:24:52 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Fri, 11 Mar 2005 14:24:52 +0100 Subject: Confused with classmethods References: <39dg9hF5u40b8U1@individual.net> Message-ID: <39dk9tF62601cU1@individual.net> > Not necessarily: > > def foo(cls): > print cls > f=classmethod(foo) > > class A: pass > > A.f = f > a=A() > a.f() Ahhh, yes, I see the minor difference - I didn't recognize it before. > > This works. Anyway, the confusion starts from the documentation of > classmethod(). Since classmethod is a *function* of builtins we can > invoke it as such from wherever we want. Sure. AFAIK it is actually a descriptor. From what I understand, when calling a descriptor on an instance it will invoke it's __get__ method and pass the instance as first argument. So classmethod just gets the __class__ from that argument and passes it to its callable together with the rest of the arguments. But this magic seems only to work if the descriptor has been fetched from a classes __dict__, not the instance __dict__. Hmm. Nice. > Moreover the documentation > sais that if the first argument is an instance, its class will be > used for the classmethod. OTOH, "class scope" is not a real thing in > python. It is just some code which is executed and then we get its > locals and use it on Class(localsDict, BasesTuple, ClassName) to make > a new class, it seems. So we can create a classmethod in any scope > and then just attach it to a class's dictionary. I'd still call the code executed inside a class statement block a "scope" - for example in a def-statement the scope is the current frame of execution, so def foo(): bar = "baz" makes the bar part of the frames local variables. Scopes just exchange or stack the dicts for name lookup. -- Regards, Diez B. Roggisch From fusionary_2000 at yahoo.com Thu Mar 3 13:36:33 2005 From: fusionary_2000 at yahoo.com (Gensek) Date: 3 Mar 2005 10:36:33 -0800 Subject: Grid not getting updated Message-ID: <1109874993.161973.110980@z14g2000cwz.googlegroups.com> I have a wxPython program, and it has a loop. I want to be able to break the loop by pushing a button. But it doesn't react to events until the loop finishes, which is sort of pointless. What's the best way to get it to work? Do I need threads? Or is there a more convenient way? From snoylr at cheqnet.net Sun Mar 27 22:26:19 2005 From: snoylr at cheqnet.net (Richard Lyons) Date: Sun, 27 Mar 2005 21:26:19 -0600 Subject: Newbie Printing Question Message-ID: I'm just starting to work with Python. Have had a little experience with basic. I am using Python on a Windows XP system. How to I print a line of output generated in a python script to a printer attached to the windows computer? From hiower4 at elitemail.org Sun Mar 20 05:25:22 2005 From: hiower4 at elitemail.org (nicke) Date: Sun, 20 Mar 2005 12:25:22 +0200 Subject: generating audio signals Message-ID: <20050320122522.405c9a4b@nadir> I'm running linux and would like to generate specific frequencies and play them(in OSS) or alternatively save them as wav files, how should I accomplish this? Using python to play and generate is not strictly necessary, as long as I can invoke the command from python. I know for example xmms can do this, but I want a command-line only solution. thanks From hongqn at gmail.com Wed Mar 30 04:01:31 2005 From: hongqn at gmail.com (Qiangning Hong) Date: 30 Mar 2005 01:01:31 -0800 Subject: distutils: package data References: <1112148325.917356.239080@f14g2000cwb.googlegroups.com> Message-ID: <1112173291.517539.95260@z14g2000cwz.googlegroups.com> ehh.. I did a little more reading and found that this function can be easily done by the new distutils parameter "package_data" in 2.4. However, I am using python2.3 :( So, my question becomes: how to emulate the package_data function in python 2.3? From rodney.maxwell at gmail.com Tue Mar 8 14:49:00 2005 From: rodney.maxwell at gmail.com (rodney.maxwell at gmail.com) Date: 8 Mar 2005 11:49:00 -0800 Subject: None in string formatting Message-ID: <1110311340.730014.50490@f14g2000cwb.googlegroups.com> Was doing some string formatting, noticed the following: >>> x = None >>> "%s" % x 'None' Is there a reason it maps to 'None'? I had expected ''. From steve at holdenweb.com Fri Mar 11 04:12:19 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 11 Mar 2005 04:12:19 -0500 Subject: Is there a short-circuiting dictionary "get" method? In-Reply-To: References: <16943.18475.568383.983546@montanaro.dyndns.org> Message-ID: Terry Reedy wrote: > "Skip Montanaro" wrote in message > news:16943.18475.568383.983546 at montanaro.dyndns.org... > >> value = d.get('x') or bsf() >> >>Of course, this bsf() will get called if d['x'] evaluates to false, not >>just >>None, > > > value = (d.get('x') is not None) or bsf() #?? > Unfortunately this will set value to True for all non-None values of d['x']. Suppose d['x'] == 3: >>> 3 is not None True >>> regards Steve From bj_666 at gmx.net Thu Mar 3 17:44:08 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 03 Mar 2005 23:44:08 +0100 Subject: binutils "strings" like functionality? References: <1109858503.101635.185640@l41g2000cwc.googlegroups.com> Message-ID: In <1109858503.101635.185640 at l41g2000cwc.googlegroups.com>, cjl wrote: > I am working on a little script that needs to pull the strings out of a > binary file, and then manipulate them with python. > > The command line utility "strings" (part of binutils) has exactly the > functionality I need, but I was thinking about trying to implement this > in pure python. > > I did some reading on opening and reading binary files, etc., and was > just wondering if people think this is possible, or worth my time (as a > learning exercise), or if something like this already exists. If you find it interesting and challenging go ahead and try it. It is possible and with the help of the 're' and 'mmap' modules it should be quite easy to filter strings out of files without the need to load them into memory at once. Ciao, Marc 'BlackJack' Rintsch From sjmachin at lexicon.net Sat Mar 19 17:38:15 2005 From: sjmachin at lexicon.net (John Machin) Date: 19 Mar 2005 14:38:15 -0800 Subject: Pre-PEP: Dictionary accumulator methods In-Reply-To: <3a3maoF66u3ggU1@individual.net> References: <1111266424.397453.43860@o13g2000cwo.googlegroups.com> <3a3maoF66u3ggU1@individual.net> Message-ID: <1111271895.425549.291530@l41g2000cwc.googlegroups.com> Reinhold Birkenfeld wrote: > John Machin wrote: > Are you kidding? If you know what "set" and "default" means, you will be > able to guess what "setdefault" means. Same goes for updateBy. > No I'm not kidding -- people from some cultures have no difficulty at all in mentally splitting up "words" like "setdefault" or the German equivalent of "Danubesteamnavigationcompany'sdirector'swife"; others from other cultures where agglutinisation is not quite so rife will have extreme difficulty. And "Updateby" sounds like a village somewhere in the Danelaw :-) From nid_oizo at yahoo.com_remove_the_ Fri Mar 18 14:15:29 2005 From: nid_oizo at yahoo.com_remove_the_ (Nicolas Fleury) Date: Fri, 18 Mar 2005 14:15:29 -0500 Subject: Import mechanism to support multiple Python versions In-Reply-To: References: Message-ID: Nicolas Fleury wrote: > import cppmymodule > > would be equivalent to: > > if sys.version == "2.4": > import cppmymodule24 as cppmymodule > elif sys.version == "2.3": > import cppmymodule23 as cppmymodule > > for all modules under the package and all modules with names beginning > with cpp (or another way to identify them). Since all my imports are absolute, my code looks more like: import root.subpackage.cppmymodule So I guess, I can add this in root/__init__.py and everything would be fine: def myimport(name, globals=None, locals=None, fromlist=None, __import__=__import__): names = name.split('.') if names[0] == 'root' and names[-1][0:3] == 'cpp': name += '%s%s' % sys.version_info[0:2] return __import__(name, globals, locals, fromlist) __builtins__['__import__'] = myimport It seems to work, is that right? Thx and regards, Nicolas From fuzzyman at gmail.com Mon Mar 14 11:19:26 2005 From: fuzzyman at gmail.com (Fuzzyman) Date: 14 Mar 2005 08:19:26 -0800 Subject: Escaping filename in http response Message-ID: <1110817166.956220.179710@l41g2000cwc.googlegroups.com> I know I *could* look this up in the relevant RFC... but I thought someone might know it off the top of their head. I'm offering files for download via a CGI. I am inserting the filename into the relevant http header. Where the filename contains spaces firefox truncates it - which is probably correct behaviour for firefox - but annoying :-) Which is the right function to escape the filename urllib.quote or urllib.quote_plus ? It's probably quote_plus....... (and I'll probably try both later... but someone might answer before that) :-) Thanks Fuzzyman http://www.voidspace.org.uk/python/index.shtml From jerf at jerf.org Tue Mar 1 14:07:08 2005 From: jerf at jerf.org (Jeremy Bowers) Date: Tue, 01 Mar 2005 14:07:08 -0500 Subject: yield_all needed in Python References: Message-ID: On Tue, 01 Mar 2005 12:42:51 -0600, Skip Montanaro wrote: > yield yield * (Mu-hu-ha-ha-ha!) From cyril.bazin at gmail.com Mon Mar 7 04:24:50 2005 From: cyril.bazin at gmail.com (Cyril BAZIN) Date: Mon, 7 Mar 2005 10:24:50 +0100 Subject: How do I import everything in a subdir? In-Reply-To: References: Message-ID: Hello, If you want to look for the files "*.py" in a directory, don't use shell command!!! You have many ways to access the content of a directory in Python. For exemple, you can use the glob module: >>> import glob >>> glob.glob('./[0-9].*') ['./1.gif', './2.txt'] >>> glob.glob('*.gif') ['1.gif', 'card.gif'] >>> glob.glob('?.gif') ['1.gif'] You might look at this page "http://docs.python.org/lib/module-glob.html". Cyril From steven.bethard at gmail.com Fri Mar 11 17:32:30 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 11 Mar 2005 15:32:30 -0700 Subject: PEP 309 (Partial Function Application) Idea In-Reply-To: References: Message-ID: <3s-dnVL4Oqfhga_fRVn-qQ@comcast.com> Chris Perkins wrote: > Random idea of the day: How about having syntax support for > currying/partial function application, like this: > > func(..., a, b) > func(a, ..., b) > func(a, b, ...) > > That is: > 1) Make an Ellipsis literal legal syntax in an argument list. > 2) Have the compiler recognize the Ellipsis literal and transform the > function call into a curried/parially applied function. > > So the compiler would essentially do something like this: > > func(a, ...) ==> curry(func, a) > func(..., a) ==> rightcurry(func, a) > func(a, ..., b) ==> rightcurry(curry(func,a), b) > > I haven't though this through much, and I'm sure there are issues, but > I do like the way it looks. The "..." really stands out as saying > "something is omitted here". Interesting idea, but I have a feeling that it probably won't fly for a couple of reasons: (1) The existing use of Ellipsis doesn't have anything to do with your suggested use. I think people are generally opposed to giving keywords/symbols in Python two very different meanings. This is one of the reasons Guido never liked the "a, b, *c = iterable" syntax. (2) Emphasis recently on python-dev has been away from syntax changes and towards expansion of the standard library. You would have to make a _very_ good case that the new syntax is merited. Generally I do like the idea -- I think a lot of the cases that people have made for keeping lambda could be discarded with something like this... But it'd need an extremely well thought out PEP (and an implementation of course) and even then, I wouldn't get my hopes up. STeVe From __peter__ at web.de Thu Mar 31 13:30:32 2005 From: __peter__ at web.de (Peter Otten) Date: Thu, 31 Mar 2005 20:30:32 +0200 Subject: split an iteration References: Message-ID: Robin Becker wrote: > Is there a fast way to get enumerate to operate over a slice of an > iterable? I think you don't need that here: e = enumerate(active_nodes) for insert_index, a in e: # ... for index, a in e: # ... Peter From vegeta.z at gmail.com Tue Mar 15 02:48:40 2005 From: vegeta.z at gmail.com (vegetax) Date: Tue, 15 Mar 2005 03:48:40 -0400 Subject: variable arguments question Message-ID: if i have a dictionary: d = {'a':2,'b':3 } l = (1,2) how can i pass it to a generic function that takes variable keywords as arguments? same thing with variable arguments, i need to pass a list of arguments to the function def asd(**kw): print kw def efg(*arg): print arg asd(d) doesnt work asd(kw = d) doesnt work efg(l) doesnt work i need to pass those as a dictionary and a list,since i dont know ahead of time if which items would have d and l From fredrik at pythonware.com Sun Mar 27 07:35:10 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sun, 27 Mar 2005 14:35:10 +0200 Subject: Get document as normal text and not as binary data References: <576fb15a.0503270342.1b8ead4e@posting.google.com> Message-ID: Markus Franz wrote: > I used urllib2 to load a html-document through http. But my problem > is: The loaded contents are returned as binary data, that means that every > character is displayed like l???t, for example. How can I get the > contents as normal text? > > My script was: > > import urllib2 > req = urllib2.Request(url) > f = urllib2.urlopen(req) adding print f.headers and checking the header fields (especially the content-type) may help you figure out what's going on... > contents = f.read() > print contents > f.close() From sjmachin at lexicon.net Mon Mar 14 07:23:35 2005 From: sjmachin at lexicon.net (John Machin) Date: 14 Mar 2005 04:23:35 -0800 Subject: will it cause any problems to open a read-only file & not close it? In-Reply-To: References: Message-ID: <1110803015.481755.278990@g14g2000cwa.googlegroups.com> Sara Khalatbari wrote: > Dear friends > In a code, I'm opening a file to read. Like : > lines = open(filename).readlines() > & I'm never closing it. > I'm not writing in that file, I just read it. > > Will it cause any problems if you open a file to read > & never close it? AFAIK, only if you try to have too many files open at one time -- many appears to be approx 512 on recent Windows (2000 and XP at least). However it's a very good habit whatever the language to close / delete / deallocate / ... any resource as soon as you no longer need it. From apardon at forel.vub.ac.be Fri Mar 25 10:16:32 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 Mar 2005 15:16:32 GMT Subject: Grouping code by indentation - feature or ******? References: <1111760130.667046.187780@f14g2000cwb.googlegroups.com> Message-ID: Op 2005-03-25, Diez B. Roggisch schreef : >> Structure/Disciplined programming is a burden in general. I have >> never found putting braces or what ever delimiter such a problem. >> I don't see people argueing that putting the right number of parenthesis >> and or brackets is an extra burden. > > Oh, not the right number. But I have seen wars waging over the correct > indention style to use. Braces behind flow control statements, or beneath, > and if the latter, indented halfways or not? > >> Use a tool for that. If people want something in python that python >> doesn't has, those people are refered to tools that provide it. >> It it works in that direction, it should also work in the other >> direction and people that would like some feature of python in >> an other language should use a tool for that. You wnat consistent >> style? Use a tool to put all your source in a consistent style. > > And what to do if two (or more) people can't decide on what convention to > use? Normally one is the project leader. He decides. > And just in case you never worked with CVS: Having mutually commits of > sourcecode that has been subject to code formatting tools often creates a > hellhole of conflicts - which is a major PITA. > >> Well to each his own. > > Amen. Why don't you use ruby? It has braces. And code blocks. And its more > liberal towards overriding builtins, which might appeal to you. I have other problems with it. I have problems with all languages currently available, so I use those which rub me wrong the least. I think the indentation syntax of python was a mistake, but for the most part it is a minor issue and it doesn't weight heavy enough to go and use an other language, although I keeping looking at the other languages. -- Antoon Pardon From harlinseritt at yahoo.com Tue Mar 15 08:19:06 2005 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 15 Mar 2005 05:19:06 -0800 Subject: Tkinter wrappers for TkTreeCtrl and Tile In-Reply-To: References: <1110882298.882635.55080@g14g2000cwa.googlegroups.com> <1110889118.739596.58440@z14g2000cwz.googlegroups.com> Message-ID: <1110892746.438130.176680@l41g2000cwc.googlegroups.com> Martin, If I may ask, who actually works on the Tkinter module? Is there a certain group that does this? I'm just curious as I've never been able to find this information. I know there are, of course, someone who develops Tk but just not sure who does this on the Python side. Thanks, Harlin From and-google at doxdesk.com Sun Mar 6 03:50:17 2005 From: and-google at doxdesk.com (and-google at doxdesk.com) Date: 6 Mar 2005 00:50:17 -0800 Subject: function with a state References: <1110096425.669042.11050@o13g2000cwo.googlegroups.com> Message-ID: <1110099017.648185.203060@o13g2000cwo.googlegroups.com> Xah Lee wrote: > is it possible in Python to create a function that maintains a > variable value? Yes. There's no concept of a 'static' function variable as such, but there are many other ways to achieve the same thing. > globe=0; > def myFun(): > globe=globe+1 > return globe This would work except that you have to tell it explicitly that you're working with a global, otherwise Python sees the "globe=" and decides you want 'globe' be a local variable. globe= 0 def myFun(): global globe globe= globe+1 return globe Alternatively, wrap the value in a mutable type so you don't have to do an assignment (and can use it in nested scopes): globe= [ 0 ] def myFun(): globe[0]+= 1 return globe[0] A hack you can use to hide statics from code outside the function is to abuse the fact that default parameters are calcuated at define-time: def myFun(globe= [ 0 ]): globe[0]+= 1 return globe[0] For more complicated cases, it might be better to be explicit and use objects: class Counter: def __init__(self): self.globe= 0 def count(self): self.globe+= 1 return self.globe myFun= Counter().count -- Andrew Clover mailto:and at doxdesk.com http://www.doxdesk.com/ From stephen.thorne at gmail.com Tue Mar 22 19:02:59 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Wed, 23 Mar 2005 10:02:59 +1000 Subject: C pointers/Python In-Reply-To: <1111462340.796275.215720@o13g2000cwo.googlegroups.com> References: <1111449164.725022.135430@f14g2000cwb.googlegroups.com> <1111454178.223461.187160@z14g2000cwz.googlegroups.com> <1111462340.796275.215720@o13g2000cwo.googlegroups.com> Message-ID: <3e8ca5c80503221602c30ba1b@mail.gmail.com> On 21 Mar 2005 19:32:20 -0800, joe at gmail.com wrote: > Can i do something like this? > > if code == CODE1: > data = 0x0 > While True: > len = len - 1 > if len == -1: > break > buffer = data > > Do i need to initialze the buffer? Please, forget everything you know about memory, pointers, and C idiom. Also, considering doing the python tutorial. There is one provided here: http://python.org/doc/tut Basically, you're not approaching this in a python-like way, and thus what should be a single line (i.e. 'return data') you're trying to turn into a painful process of copying data from one memory location to another. This is acceptable in the C world, and not appropriate in the python world. I would suggest you define your problem in broader terms (i.e. "I am trying to interpret data that is coming over a socket, my packet structure looks like this ..., how do I marshall dispatch that to callbacks so I can talk the protocol properly? Here is a link to the working C code http://...") and there is a large group of wonderful people here that would love to show you the pythonic way of achieving your goal. -- Stephen Thorne From cam.ac.uk at mh391.invalid Wed Mar 9 17:44:28 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 09 Mar 2005 22:44:28 +0000 Subject: An Odd Little Script In-Reply-To: References: Message-ID: Greg Lindstrom wrote: > I have a file with varying length records. All > but the first record, that is; it's always 107 bytes long. What I would > like to do is strip out all linefeeds from the file, read the character > in position 107 (the end of segment delimiter) and then replace all of > the end of segment characters with linefeeds, making a file where each > segment is on its own line. Hmmmm... here's one way of doing it: import mmap import sys DELIMITER_OFFSET = 107 data_file = file(sys.argv[1], "r+w") data_file.seek(0, 2) data_length = data_file.tell() data = mmap.mmap(data_file.fileno(), data_length, access=mmap.ACCESS_WRITE) delimiter = data[DELIMITER_OFFSET] for index, char in enumerate(data): if char == delimiter: data[index] = "\n" data.flush() There are doubtless more efficient ways, like using mmap.mmap.find() instead of iterating over every character but that's an exercise for the reader. And personally I would make extra copies ANYWAY--not doing so is asking for trouble. -- Michael Hoffman From johan at mailinator.com Sat Mar 12 19:23:07 2005 From: johan at mailinator.com (Johan) Date: 12 Mar 2005 18:23:07 -0600 Subject: pygtk help Message-ID: [x-posted to PyGTk mailing list as well] Hello! I'm trying to figure out how to use PYGTK to implement a rudimentary UI: I want to have an Image as the background, and then be able to put buttons (eventually icons, but buttons for now) The PyGTK FAQ (pygtk.org) has some suggestions, but they have failed to clear up the issue. Using their suggestions as a starting point, I've arrived at the below. However, it fails in that I can't seem to place the image behind the button. There is a FAQ entry specifically on this at PyGTK.org, but that fails to show the pixmap (it is obscured completely when we place a button in the Fixed widget), and fails to allow the pixmap to be scrolled. Can anyone show a minimal example of how I might achieve having the pixmap as the background of the Fixed widget? Thanks Johan def __init__(self): # create the main window, and attach delete_event signal to terminating # the application window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.connect("delete_event", self.close_application) window.connect("destroy", self.close_application) window.set_border_width(0) hbox= gtk.HBox() window.add(hbox) hbox.show() swin1 = gtk.ScrolledWindow() swin1.set_policy(gtk.POLICY_ALWAYS, gtk.POLICY_ALWAYS) swin1.set_size_request(600, 600) hbox.add(swin1) swin1.show() fbox1 = gtk.Fixed() swin1.add_with_viewport(fbox1) fbox1.show() ebox1 = gtk.EventBox() fbox1.put(ebox1,0,0) ebox1.show() image1 = gtk.Image() image1.set_from_file("/home/johan/bg.jpg") ebox1.add(image1) image1.show() widgetinfo( image1) b = gtk.Button("FOO") fbox1.put(b, 200,200) b.show() widgetinfo(b) ebox1.set_events(gtk.gdk.BUTTON_PRESS_MASK) ebox1.connect("button_press_event", self.button_clicked) window.show() From roy at panix.com Tue Mar 1 21:57:41 2005 From: roy at panix.com (Roy Smith) Date: Tue, 01 Mar 2005 21:57:41 -0500 Subject: Help- Simple recursive function to build a list References: Message-ID: In article , actuary77 wrote: > I am trying to write simple recursive function to build a list: > > > def rec(n,alist=[]): > _nl=alist[:] > print n,_nl > if n == 0: > print n,_nl > return _nl > else: > _nl=_nl+[n] > rec(n-1,_nl) > > _nl=[] > _nl=rec(4) > print _nl > > ### shouldn't this work? > > _nl=rec(4) > > > > > The output is: > 4 [] > 3 [4] > 2 [4, 3] > 1 [4, 3, 2] > 0 [4, 3, 2, 1] > 0 [4, 3, 2, 1] > None > None > > > Question: > ============ > Why isn't the function returning a list? > Why is function returning None? I'm not 100% sure what you're trying to do here, but I suspect you left a "return" out of the else block, i.e. "return rec(n-1, _nl)". That would certainly explain why it's returning None. What problem are you trying to solve, or are you just experimenting with recursion? From jjreavis at gmail.com Wed Mar 9 16:14:33 2005 From: jjreavis at gmail.com (Jeff Reavis) Date: 9 Mar 2005 13:14:33 -0800 Subject: Web framework References: <1110385222.509176.44740@g14g2000cwa.googlegroups.com> Message-ID: <1110402873.084493.227310@o13g2000cwo.googlegroups.com> You may also want to look at Spyce. It is similar to JSP,PHP, or ASP. There are some good docs and examples at the site. http://spyce.sourceforge.net/ -jjr From noreply at python.org Tue Mar 1 07:06:29 2005 From: noreply at python.org (Mail Delivery Subsystem) Date: Tue, 1 Mar 2005 13:06:29 +0100 Subject: MDaemon Warning - virus found: Returned mail: see transcript for details Message-ID: <20050301120734.5EAE51E4007@bag.python.org> ******************************* WARNING ****************************** Este mensaje ha sido analizado por MDaemon AntiVirus y ha encontrado un fichero anexo(s) infectado(s). Por favor revise el reporte de abajo. Attachment Virus name Action taken ---------------------------------------------------------------------- document.zip Email-Worm.Win32.Mydoom.m Removed ********************************************************************** The original message was included as attachment From radam2 at tampabay.rr.com Tue Mar 22 17:27:25 2005 From: radam2 at tampabay.rr.com (Ron) Date: Tue, 22 Mar 2005 22:27:25 GMT Subject: Anonymus functions revisited References: <1111473462.162737.188230@o13g2000cwo.googlegroups.com> <423ff0b8$0$1549$636a15ce@news.free.fr> <42402644$0$5377$626a14ce@news.free.fr> <42408017$0$22689$626a14ce@news.free.fr> <2h01415clt8o9p3eut7mf73jrf8fv6jpva@4ax.com> Message-ID: On Tue, 22 Mar 2005 21:56:57 GMT, Ron wrote: >Why should a function not create a local varable of an argument if the >varable doesn't exist and a default value is given? ok... thought it out better. :) Getting a default into a function isn't the problem. Returning the value to a varable that doesn't exist is. So then the question is ... is there a way for a function to create a varable in it's parents namespace that persists after the function is done? From Serge.Orlov at gmail.com Fri Mar 18 14:59:50 2005 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 18 Mar 2005 11:59:50 -0800 Subject: Import mechanism to support multiple Python versions In-Reply-To: References: Message-ID: <1111175990.544924.103980@g14g2000cwa.googlegroups.com> Nicolas Fleury wrote: > Hi, > I'm trying to support two Python versions at the same time and I'm > trying to find effective mechanisms to support modules compiled in > C++ transparently. > > All my code in under a single package. Is it possible to override > the import mechanism only for modules under that package and > sub-packages so that?: > > import cppmymodule > > would be equivalent to: > > if sys.version == "2.4": > import cppmymodule24 as cppmymodule > elif sys.version == "2.3": > import cppmymodule23 as cppmymodule > > for all modules under the package and all modules with names > beginning with cpp (or another way to identify them). I used the following approach application-wide: ===== The very start of main file === resolve_package_dependencies() import package def main(): ... # boilerplate at the end of main file def resolve_package_dependencies(): if sys.version_info[0:2] == (2,5): import package1 sys.modules["package"] = sys.modules["package1"] else: import package2 sys.modules["package"] = sys.modules["package2"] ===================================== I've never needed that for packages like you, but as far as I remember package specific modules are stored like "package.module" so aliasing "package45" with "package" in your case will look like sys.modules[__name__+".package"] = sys.modules[__name__+".package45"] Serge. From fredrik at pythonware.com Tue Mar 29 08:43:19 2005 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 29 Mar 2005 15:43:19 +0200 Subject: passing keyword args as a parameter References: Message-ID: "max(01)*" wrote: > see what i mean? not really, but maybe arg = {"pc2": 666, "pc1": "Addio..."} fun_con_pc(**arg) is what you want? From andreasp+python at qbcon.com Tue Mar 1 02:07:14 2005 From: andreasp+python at qbcon.com (Andreas Pauley) Date: Tue, 1 Mar 2005 09:07:14 +0200 (SAST) Subject: User Security (Roles & Permissions) In-Reply-To: References: Message-ID: On Mon, 28 Feb 2005, Andreas Pauley wrote: > Hi all, > > I'm starting with a Point of Sale system (QT gui, MySQL db) and I'm wondering > if there are any user management/user security modules available that can be > reused independently of the specific system that you write. > > I think something similar to the roles & permission scheme of Zope would > work, were I can assign certain functionality/permissions to a role, and then > assign each user a role. > > I'd prefer not to fully jump into Zope just yet, because although it has just > about all the features you can think of, it is also fairly complex (for me at > least). It seems that its quite possible to use the security system of Zope 3 outside of the Zope environment in standard Python. I just copied the relevant zope package dirs to my own source tree and I was able to run the supplied Python examples. Regards, Andreas From simon.brunning at gmail.com Tue Mar 8 09:57:58 2005 From: simon.brunning at gmail.com (Simon Brunning) Date: Tue, 8 Mar 2005 14:57:58 +0000 Subject: quick question In-Reply-To: <54668D97C0199943A454516A5FF6481E58A61B@EXCHUS001.AD.MLP.COM> References: <54668D97C0199943A454516A5FF6481E58A61B@EXCHUS001.AD.MLP.COM> Message-ID: <8c7f10c6050308065715d8d2b3@mail.gmail.com> On Mon, 7 Mar 2005 18:58:20 -0500, Leeds, Mark wrote: > > I have a string variable say "8023 " and > > I want to get rid of the beginning > > And ending quotes. Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> my_string = '"8023 "' >>> my_string '"8023 "' >>> my_string.strip('"') '8023 ' -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From cappy2112 at gmail.com Wed Mar 23 20:01:19 2005 From: cappy2112 at gmail.com (Cappy2112) Date: 23 Mar 2005 17:01:19 -0800 Subject: Submission for Python Limmerick Contest References: <7be3f35d.0503220832.60480dc8@posting.google.com> Message-ID: <1111626078.995158.176780@z14g2000cwz.googlegroups.com> "The First Python function ever written" (takes place in the Garden of Eden" Guido sayeth "I will write def foo():" "Hmm, I could use an import, or two", Satan said, in a whirl, "Why not write it in Perl?", and the second function ever written - def foo_you(): From runsun at gmail.com Mon Mar 28 09:51:12 2005 From: runsun at gmail.com (runsun pan) Date: 28 Mar 2005 06:51:12 -0800 Subject: list-comprehension and map question (simple) In-Reply-To: References: Message-ID: <1112021472.288113.155120@l41g2000cwc.googlegroups.com> I remember reading somewhere that the map, filter, reduce are much faster than list comp. From cam.ac.uk at mh391.invalid Wed Mar 16 04:59:19 2005 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 16 Mar 2005 09:59:19 +0000 Subject: Good use for Jython In-Reply-To: <1110959656.002203.316010@f14g2000cwb.googlegroups.com> References: <1110959656.002203.316010@f14g2000cwb.googlegroups.com> Message-ID: Mike Wimpe wrote: > Other than being used to wrap Java classes, what other real use is > there for Jython being that Python has many other GUI toolkits > available? Also, these toolkits like Tkinter are so much better for > client usage (and faster) than Swing, so what would be the advantage > for using Jython? What ever gave you the impression that Jython was targeted only at people who wanted to do GUI development? -- Michael Hoffman From tim.leeuwvander at nl.unisys.com Fri Mar 11 08:29:35 2005 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 11 Mar 2005 05:29:35 -0800 Subject: RELEASED Python 2.4.1, release candidate 1 In-Reply-To: References: <200503110138.02569.anthony@python.org> <4230FAA5.4070309@v.loewis.de> Message-ID: <1110547775.464281.207790@g14g2000cwa.googlegroups.com> Hi, The new installer worked fine for me (WinXP1), but I wasn't sure if I could install over the old version and have it work properly / remove the old version from the 'Add / remove programs' list. It suggested a default location on the C: drive but the old version was installed on the D: drive (and that's where I want it to be installed). When I pointed it to the old location it didn't complain about the old files, but didn't give me an indication either of going to do an update. So I got confused and uncertain. I decided to remove the old Python2.4 first, then reboot and reinstall. (Is reboot really needed?) And then afterwards it did complain about seeing files still in the D:\Python24 directory. Perhaps nicer if the installer could give feedback like 'Old installation found; will update to new version' or something like that. But that can be for 2.4.2 or a later time. cheers, --Tim From bj_666 at gmx.net Tue Mar 22 19:32:35 2005 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 23 Mar 2005 01:32:35 +0100 Subject: problems with =?iso-8859-1?q?=C2?= character References: <1111521139.657563.55410@o13g2000cwo.googlegroups.com> Message-ID: In <1111521139.657563.55410 at o13g2000cwo.googlegroups.com>, jdonnell wrote: > I have a mysql database with characters like ? ? ?? in it. I'm > trying to write a python script to remove these, but I'm having a > really hard time. > > [...] > > The other odd thing is that the ? character shows up as two spaces if > I print it to the terminal from mysql, but it shows up as ? when I > print from the simple script above. > What am I doing wrong? Is it possible that your DB stores strings UTF-8 encoded? The byte sequence '\xc2\xa0' which displays as '? ' in latin-1 encoding is a non breakable space character. Ciao, Marc 'BlackJack' Rintsch From xavier_onasis at hotmail.com Wed Mar 16 19:01:47 2005 From: xavier_onasis at hotmail.com (Kotlin Sam) Date: Wed, 16 Mar 2005 19:01:47 -0500 Subject: I can do it in sed... Message-ID: I have spent so much time using sed and awk that I think that way. Now, when I have to do some Python things, I am having to break out of my sed-ness and awk-ness, and it is causing me problems. I'm trying. Honest! Here are the two things that I'm trying to do: In sed, I can print every line between ^start to ^end by using /^start/,/^end/p. It's quick, easy, and doesn't take much time. Is there a way to do this easily in Python? Also, I frequently use something like s/^[A-Z]/~&/ to pre-pend a tilde or some other string to the beginning of the matched string. I know how to find the matched string, but I don't know how to change the beginning of it while still keeping the matched part. If I were able to stay in the *nix environment for all my work, I could do it with these tools and the beloved pipe(|), but that isn't my lot in life. I would do it in Perl, but, frankly, it gives me headaches even looking at it. Any ideas? Thanks, Lance From gsakkis at rutgers.edu Mon Mar 21 19:02:19 2005 From: gsakkis at rutgers.edu (George Sakkis) Date: Mon, 21 Mar 2005 19:02:19 -0500 Subject: Set literals References: Message-ID: <3a95k6F680ptuU1@individual.net> "Delaney, Timothy C (Timothy)" wrote: > > How about overloading curly braces for set literals, as in > > > >>>> aSet = {1,2,3} > > > > - It is the standard mathematic set notation. > > - There is no ambiguity or backwards compatibility problem. > > - Sets and dicts are in many respects similar data structures, so why > > not share the same delimiter ? > > This was the proposed syntax (with {-} being the empty set - there's the > ambiguity). The issue may be revisited for Python 3K, but for now there > will not be syntax support for sets. > > Read the section on 'Set Notation' in: > http://www.python.org/peps/pep-0218.html > > Tim Delaney Thanks for the link; obviously, I wasn't aware of the proposal and its rejection. looking-forward-to-python-3K-ly yours, George From gh at ghaering.de Sun Mar 13 21:25:32 2005 From: gh at ghaering.de (Gerhard Haering) Date: Mon, 14 Mar 2005 03:25:32 +0100 Subject: [ANN] pysqlite 2.0.alpha2 Message-ID: <20050314022532.GA14652@mylene.ghaering.de> pysqlite 2.0.alpha2 =================== The last release was back in Nov. 2004, but pysqlite 2 development is going on faster now. So it's time for another alpha release to collect feedback. Please report any bugs you find on the pysqlite mailing list, or even better on the trac tracking system at http://initd.org/tracker/pysqlite Downloads at Sourceforge: http://sourceforge.net/project/showfiles.php?group_id=54058&package_id=134545 The project itself at http://pysqlite.org/ Changes since pysqlite 2.0.alpha1 ================================= Namespaces change: - the DB-API module is now called pysqlite2.dbapi2 instead of sqlite, you typically import it using "from pysqlite2 import dbapi2 as sqlite" DB-API compliance: - implemented all module-level constants and functions that are required for DB-API compliance Type system: << Type conversion SQLite => Python >> ** SQLite types mode (default ** - nothing happens behind your back. if you SELECT, you get back the types SQLite reports. So, you will only get strings, ints, floats, and BLOBs (BLOBs as Python buffer objects) ** pysqlite types mode (have to activate explicitly) ** - the returned type depends on the decleared column for the SELECTed data. To use it successfully, you must register converters for the column types (see below). You can also set the declared column types explicitly using the coltypes property of cursors (see below) - new method register_converter(coltypes, converter) for connection objects: * con.register_converter("int": int) * con.register_converter("unicode": unicode) * con.register_converter("boolean": bool) * con.register_converter("foo": lambda x: "<%s>" % x) * class Bar: ... con.register_converter("bar": Bar) - new property coltypes of cursor objects: cur.coltypes = {"col1": int} cur.execute("select foo as col1 from bar") << Type conversion Python => SQLite >> - Like in PEP 246 (Object Adaptation) - the default protocol does nothing, except handle Unicode strings - the protocol's __adapt__ returns the SQLite value directly at the moment (this will perhaps change in the next release) - example protocol: class P(dbapi2.SQLitePrepareProtocol): def __adapt__(self, obj): if isinstance(obj, Point): return "(%s/%s)" % (obj.x, obj.y) else: return dbapi2.SQLitePrepareProtocol.__adapt__(self, obj) con = sqlite.connect(":memory:", more_types=True, prepareProtocol=P()) Connect call: - Syntax is now: con = sqlite.connect(database, timeout, protocol, more_types) * timeout: timeout parameter in seconds, until error raised if concurrent access. in alpha1, it just failed immediately * protocol: see Type system * more_types: set to true if you want to use the pysqlite types mode instead of the default SQLite one Misc.: - pysqlite.dbapi2 now has constants version and version_info -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From rpmuller at gmail.com Tue Mar 8 11:38:57 2005 From: rpmuller at gmail.com (rick_muller@yahoo.com) Date: 8 Mar 2005 08:38:57 -0800 Subject: Format strings that contain '%' Message-ID: <1110299937.861208.263140@f14g2000cwb.googlegroups.com> I'm trying to do something along the lines of >>> print '%temp %d' % 1 Traceback (most recent call last): File "", line 1, in ? ValueError: unsupported format character 't' (0x74) at index 1 although, obviously I can't do this, since python thinks that the '%t' is a format string. I've tried obvious permutations like >>> print '\%temp %d' % 1 which also doesn't work. For (template) reasons, I can't do >>> print '%s %d' % ('%temp',1) Will anything else work here? From vze4rx4y at verizon.net Fri Mar 18 23:31:19 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sat, 19 Mar 2005 04:31:19 GMT Subject: Pre-PEP: Dictionary accumulator methods References: Message-ID: [Roose] > I like this, it is short, low impact, and makes things more readable. I > tend to go with just the literal way of doing it instead of using get and > setdefault, which I find awkward. Thanks. Many people find setdefault() to be an oddball. > But alas I had a my short, low impact, useful suggestion and I think it > died. It was for any() and all() for lists. Actually Google just released > their "functional.py" module on code.google.com with the exact same thing. > Except they are missing the identity as a default which is very useful, i.e. > any(lst, f=lambda x: x) instead of any(lst, f). > > Maybe you can tack that onto your PEP :) Py2.5 is already going to include any() and all() as builtins. The signature does not include a function, identity or otherwise. Instead, the caller can write a listcomp or genexp that evaluates to True or False: any(x >= 42 for x in data) If you wanted an identify function, that simplifies to just: any(data) Raymond Hettinger From peter at engcorp.com Sat Mar 12 08:15:23 2005 From: peter at engcorp.com (Peter Hansen) Date: Sat, 12 Mar 2005 08:15:23 -0500 Subject: newbie: dictionary - howto get key value In-Reply-To: <1110612528.859949.119450@o13g2000cwo.googlegroups.com> References: <42308a5b$0$28852$626a14ce@news.free.fr> <1110612528.859949.119450@o13g2000cwo.googlegroups.com> Message-ID: John Machin wrote: >>G. V?lkl wrote: >>>I use a dictionary: >>>phone = {'mike':10,'sue':8,'john':3} > > Of course in the real world using given name as a unique key is > ludicrous: 'mike' is a.k.a. 'michael' (or 'mikhail' or 'michele' (which > may be a typo for 'michelle')), and if there's only one 'sue' in your > little black book you need to get out more :-) Maybe they're the names of his children... ;-) Of course, one could have multiple children with the same name under any or all of the following conditions: 1. insanity (perhaps of the parents or the children?) 2. remarriage (i.e. step-children) 3. sheer forgetfulness 4. laziness ("meet Brian, Brian, and Brian") This last is the closest I can come to making this post on-topic... sorry! :-) -Peter From sjmachin at lexicon.net Mon Mar 14 17:06:15 2005 From: sjmachin at lexicon.net (John Machin) Date: 14 Mar 2005 14:06:15 -0800 Subject: is there a problem on this simple code In-Reply-To: References: <1110673986.226532.246050@g14g2000cwa.googlegroups.com> <1110677750.240962.261130@z14g2000cwz.googlegroups.com> <1110690057.935924.81550@l41g2000cwc.googlegroups.com> <2cad20900503122256d1fb397@mail.gmail.com> <8p0831pbv2k26sr843s0tag312a0mmfs4m@4ax.com> <1110747976.300591.138830@g14g2000cwa.googlegroups.com> Message-ID: <1110837975.557076.310680@o13g2000cwo.googlegroups.com> jrlen balane wrote: > why is it that here: > > 1)rx_data = ser.read(10) > (rx_command, rx_msg_no, rx_no_databyte, temp1, temp2, pyra1, > pyra2, voltage, current, rx_checksum) = unpack('10B', rx_data) > print rx_command, rx_msg_no, rx_no_databyte, temp1, temp2, pyra1, > pyra2, voltage, current, rx_checksum > > >>> type (rx_command) > > > but here: > > 2)rx_data_command = ser.read() Are you sure you have really have read() -- which will read all available data -- or read(1) -- which will read just one byte??? > (rx_command) = unpack('1B', rx_data_command) > > >>> type (rx_command) > > > how can i make rx_command of type 'int' if i am to use 2)? unpack returns a tuple. In 1) you unpack it. In 2) you don't unpack it. either do this: (rx_command,) = unpack('1B', rx_data_command) # unpack tuple or this: rx_command = unpack('1B', rx_data_command)[0] # grab 1st element of tuple or, simply, to get what you want, just do this: rx_command = ord(ser.read(1)) > > @sir John > the reason why my first post all starts with '70' , which is what i > really wanted to happen, is that it is buffered. the microcontroller > sends data at a very fast rate, that the program just retrieve data > from the buffer. so basically, they are not "real time". but there are > also cases where the command is in other position. the good thing is, > it remains in that position throughout... It wasn't doing that before; In the second posting with examples, there were some that were a MIXTURE of (a) 70 as the first byte of 10 (b) 70 as the fourth byte of 10 (128 128 103 70 2 6 64 64 192 0) > > i want to make the program show data in "real time" so everytime i am > able to read data, i immediately use flushInput(), to erase data from > the buffer. How large is the buffer? > > so i what i want to do now is to search for the rx_command first > ('70') just so i know where my data should start. OK, so NOW you are saying that the microcontroller is pumping out data continuously, it's not one response to each of your "67" commands??? In that case what I'd suggest you do is to read 19 bytes from the serial port (with time-out, I'd suggest; give up if you don't get 19 bytes returned), and for each k in range(9), test for: (a) byte[k] == 70 (b) byte[k+2] == 6 (c) checksum(byte[k:k+10]) == 0 If you don't get a valid data packet, give up. This should snatch one valid data packet (if there are any) from the torrent. From andy2O at hotmail.com Fri Mar 11 08:26:34 2005 From: andy2O at hotmail.com (andy2O at hotmail.com) Date: 11 Mar 2005 05:26:34 -0800 Subject: (Newbie) Restricting inherited methods to operate on element from same subclass References: Message-ID: <1110547594.017110.189880@z14g2000cwz.googlegroups.com> >Assuming that A is a new-style class then if they have to be >exactly the same type compare the types Ah-ha! I didn't know that. >if the 'other' value can be a subclass of self: > > def join(self, other): > if not isinstance(other, type(self)): > raise whatever Simple and neat! >If A is an old-style class then you would have to compare >the __class__ attribute: self.__class__ != other.__class__ That answered my question perfectly. I'll read up on the new style classes and pick whichever of your solutions fits best. Many thanks, Andy. From news at fluidobjects.com Fri Mar 4 06:28:48 2005 From: news at fluidobjects.com (Maxim Khesin) Date: Fri, 04 Mar 2005 11:28:48 GMT Subject: [announcement] - python graph library Message-ID: Hello Folks, I recently started working on a graph-algorithms library in Python. What makes this one different from the other couple of libs that are available is a heavy influence from the C++ Boost Graph Library. There are IMO a lot of good ideas there, so I am attempting to translate the spirit of it into Python without loosing the Pythonness :). There is no official code release so far, but I have been blogging ideas and code snippets here: http://pythonzweb.blogspot.com/. Your comments are most welcome (you can leave them right on the blog).I also wanted to tap your opinion on naming this thing. There is (duh) already PyGL and PGL names associated with python (but not graph libs) floating around, but as they are not so well-known as far as I can tell I do not mind taking them on and stealing the name. What do you guys think? From hseritt at pythonian.com Fri Mar 4 22:40:55 2005 From: hseritt at pythonian.com (Harlin Seritt) Date: Fri, 4 Mar 2005 22:40:55 -0500 Subject: [announcement] - python graph library References: Message-ID: "Maxim Khesin" wrote in message news:QDXVd.23198$qn2.4287835 at twister.nyc.rr.com... > Hello Folks, > I recently started working on a graph-algorithms library in Python. What > makes this one different from the other couple of libs that are > available is a heavy influence from the C++ Boost Graph Library. There > are IMO a lot of good ideas there, so I am attempting to translate the > spirit of it into Python without loosing the Pythonness :). There is no > official code release so far, but I have been blogging ideas and code > snippets here: http://pythonzweb.blogspot.com/. Your comments are most > welcome (you can leave them right on the blog).I also wanted to tap your > opinion on naming this thing. There is (duh) already PyGL and PGL names > associated with python (but not graph libs) floating around, but as they > are not so well-known as far as I can tell I do not mind taking them on > and stealing the name. What do you guys think? pygribs :-) -- Harlin's Internet Villa: http://seritt.org From jackni41 at hotmail.com Wed Mar 2 10:32:49 2005 From: jackni41 at hotmail.com (Jack) Date: 2 Mar 2005 07:32:49 -0800 Subject: Zope - Restrict Acquisition Question Message-ID: <1109777569.658001.171680@z14g2000cwz.googlegroups.com> I have the following requirement for Zope: I need to use Zope as a web cloning tool. The directory structure is as follows: ->>Core Folder ->>Client 1 ->>Client 2 ... ->>Client n 1] Client 1 and Client 2 need to acquire from the Core Folder. 2] Client 2 must not acquire from Client 1. 3] Client 1 must not acquire from Client 2. Note: I know that creating a Zope object named Client 2 and putting it into Client 1's folder will work but there will be about 50+ clients. So that would require 50+ objects in each client folder. There's got to be a better way ... Any Ideas? Thanks! From benn at cenix-bioscience.com Wed Mar 30 14:00:45 2005 From: benn at cenix-bioscience.com (Neil Benn) Date: Wed, 30 Mar 2005 21:00:45 +0200 Subject: CGI, FieldStorage and Filename In-Reply-To: <424AF64E.10302@cenix-bioscience.com> References: <424AF64E.10302@cenix-bioscience.com> Message-ID: <424AF75D.1010900@cenix-bioscience.com> Neil Benn wrote: > Hello, > > I'm writing a simple cgi script and want to be able to access > the filename in a FieldStorage file instance. I have successfully > manmaged to access the file as a 'file-like object' by using the > simple code of : > Sorry, split the filename on path not pathext.. have a nice day if you are in a different time zone than me! Cheers, Neil -- Neil Benn Senior Automation Engineer Cenix BioScience BioInnovations Zentrum Tatzberg 46 D-01307 Dresden Germany Tel : +49 (0)351 4173 154 e-mail : benn at cenix-bioscience.com Cenix Website : http://www.cenix-bioscience.com From martin at v.loewis.de Tue Mar 15 19:06:55 2005 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 16 Mar 2005 01:06:55 +0100 Subject: Python-list Digest, Vol 18, Issue 208 In-Reply-To: <113cbf0cij5pu88@corp.supernews.com> References: <20050314025012.203891E4009@bag.python.org> <113atfbannuhp04@news.supernews.com> <113c2utqil2tdcc@corp.supernews.com> <113cbf0cij5pu88@corp.supernews.com> Message-ID: <4237789F.6050006@v.loewis.de> Jeff Shannon wrote: > I'd be in favor of that, unless someone can come up with a compelling > current use-case for octal literals. Existing code. It may use octal numbers, and it would break if they suddenly changed to decimal. Not only that - breakage would be *silent*, i.e. the computations would just use incorrect numbers. You could make breakage explicit, by disallowing leading zeroes in integer literals - but still, programs would break. As for functional use-cases: os.chmod is the typical example: os.chmod("/tmp/bla", 0660) gives rw-rw---- access to /tmp/bla. Unix permission line up nicely with octal numbers. Regards, Martin From steve at holdenweb.com Fri Mar 4 18:02:00 2005 From: steve at holdenweb.com (Steve Holden) Date: Fri, 04 Mar 2005 18:02:00 -0500 Subject: Python 2.4 removes None data type? In-Reply-To: References: <1109972831.320289.275980@f14g2000cwb.googlegroups.com> Message-ID: <4228E8E8.6030202@holdenweb.com> Warren Postma wrote: > gaudetteje at gmail.com wrote: > >> I just read in the 'What's New in Python 2.4' document that the None >> data type was converted to a constant: >> http://python.org/doc/2.4/whatsnew/node15.html > > > Implication: A long standing wart in Python now gone. Its time to > gloat. Are there any really evil glitches LEFT in Python? Now go look at > Perl and come back and say "Thank-deity-of-my-choice-I'm-using-Python". > > Remaining warts that won't disappear: print >> file, stuff @decorator regards Steve -- Meet the Python developers and your c.l.py favorites March 23-25 Come to PyCon DC 2005 http://www.pycon.org/ Steve Holden http://www.holdenweb.com/ From djc at object-craft.com.au Sun Mar 20 18:15:36 2005 From: djc at object-craft.com.au (Dave Cole) Date: Mon, 21 Mar 2005 10:15:36 +1100 Subject: Sybase module 0.37pre2 released Message-ID: <423E0418.6080405@object-craft.com.au> WHAT IS IT: The Sybase module provides a Python interface to the Sybase relational database system. It supports all of the Python Database API, version 2.0 with extensions. NOTES: This release contains a number of small bugfixes and patches received from users. I have been unable to find the source of the memory leak reported here: http://www.object-craft.com.au/pipermail/python-sybase/2004-December/000346.html The test program I wrote follows: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - import sys import Sybase db = Sybase.connect(..., auto_commit=True) db.execute(''' if exists (select name from sysobjects where name = "sp_test_leak") begin drop procedure sp_test_leak end ''') db.execute(''' create procedure sp_test_leak @arg int as select @arg ''') for i in range(200): for j in range(1000): c = db.cursor() c.callproc('sp_test_leak', {'@arg': 12345 }) sys.stdout.write('%3d\r' % i) sys.stdout.flush() sys.stdout.write('\n') - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - If someone is able to modify this and come up with a leaking result I am interested in working on the fix. You can build for FreeTDS like this: python setup.py build_ext -D HAVE_FREETDS -U WANT_BULKCOPY python setup.py install The module is available here: http://www.object-craft.com.au/projects/sybase/download/sybase-0.37pre1.tar.gz The module home page is here: http://www.object-craft.com.au/projects/sybase/ CHANGES SINCE 0.36: * Cursor state initialisation fix from Skip Montanaro. * Callback declaration fix on Windows from Vadim Beloborodov. * Cursor output parameters now work when parameters are passed as a sequence. * Output parameters now work for FreeTDS 0.62.4. 1> create procedure sp_test_output 2> @num int, @result int output 3> as 4> select @result = @num 5> go params = c.callproc('sp_test_output', {'@num': 12345, '@result': Sybase.OUTPUT(1)}) print params['@result'] * The CS_STATUS_RESULT result set is now consumed internally in the Cursor and does not appear in the result sets consumed by the fetch and nextset methods. The return value from the stored procedure is available in the .return_status member of the Cursor. It will only contain a meaningful value once all of the row result sets have been consumed. Note that this does not work with FreeTDS 0.62.4. The return_status seems to always be 0. Research shows that the problem is probably in the CT emulation layer as tsql displays the correct value, but sqsh displays 0. * Output hook patch from Ty Sarna has been applied. * Applied patch from Andre Sedinin to improve error handling. * Improved detection of SYBASE_OCS. - Dave -- http://www.object-craft.com.au From mfranke78 at yahoo.de Sun Mar 13 03:26:50 2005 From: mfranke78 at yahoo.de (Marek Franke) Date: Sun, 13 Mar 2005 09:26:50 +0100 Subject: Linux Multimedia System Message-ID: <423477c6_1@news.arcor-ip.de> Hi there, we have started with some people from our LUG (Linux User Group) a 'little' project, called LMMS (Linux Multimedia System). When it's 'finished' it shall be a window-manager for use on TV and handle with joysticks/gamepads. As the name says, it is for multimedia-applications, like listening to music, watching videos and maybe playing some games. The idea is to create a gui for application like mplayer, ogg123, mpg123, cdrecord etc. For now there are some widgets for displaying images, labels and some messages. Actually there is a working LMMS with a little menu, an image-viewer and a CD-player. Supperted joysticks/gamepads are Gravis Gamepad Pro, Nintendo's SNES Pads, Microsoft's X-Box pad and keyboard. The whole project is written in python/pygame and can be found here: http://home.arcor.de/mfranke78/ There is a little mailinglist too (German & Yahoo): http://de.groups.yahoo.com/group/dulugprojekt/ Remember that the whole project is very basic for now! But it seems to work. Greets, Marek From andreis at stud.cs.uit.no Wed Mar 2 06:50:01 2005 From: andreis at stud.cs.uit.no (=?ISO-8859-1?Q?Andr=E9_S=F8reng?=) Date: Wed, 02 Mar 2005 12:50:01 +0100 Subject: Regular Expressions: large amount of or's In-Reply-To: References: <4224c79c$1_3@newspeer2.tds.net> Message-ID: Ola Natvig wrote: > Andr? S?reng wrote: > >> >> >> Yes, but I was looking for a solution which would scale. Searching >> through the same string 10000+++ times does not seem like a suitable >> solution. >> >> Andr? > > > Just for curiosity, what would a regexp do? Perhaps it's a clue in how > you could do this in the way regexp's are executed. > > ola > I think this article provides me with what I was looking for: http://alexandria.tue.nl/extra1/wskrap/publichtml/200407.pdf Enough info there to keep me going for some while. From steven.bethard at gmail.com Mon Mar 14 18:46:36 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 14 Mar 2005 16:46:36 -0700 Subject: Second argument to super(). In-Reply-To: References: <1110396167.53bd67fed97c9e826a92b284283b1455@teranews> <1130c6toefobh1a@news.supernews.com> Message-ID: Steve Holden wrote: > John Roth wrote: >> What happens with the second operand is a bit of >> sleight of hand. The object returned from super() >> gives you access to the methods on the next level up the >> mro, however when you use it to invoke a method, >> then the 'self' passed to that method is the second >> object, not the instance returned from super(). >> > This is a key point. I wonder whether we might use this thread to draft > a patch to the docs for submission on SourceForge? Done: www.python.org/sf/1163367 It's nowhere near perfect, but I think it at least somewhat more accurately reflects the actual workings of super. If you have any good clarifications or rewordings, please feel free to add them to the tracker. While I also agree that the documentation needs a major revamp to properly show the interworkings of all the new-style class components, a patch for super is about the best I can offer at the moment. =) STeVe From ali.jan at gmail.com Thu Mar 31 02:26:38 2005 From: ali.jan at gmail.com (M Ali) Date: 30 Mar 2005 23:26:38 -0800 Subject: Actor pattern in GUI References: <8acb5ef8.0503290407.76392bd@posting.google.com> Message-ID: <8acb5ef8.0503302326.4d1fc028@posting.google.com> Hmm... no takers? Too bad, the pattern and it's implementation in python is pretty interesting... ali.jan at gmail.com (M Ali) wrote in message news:<8acb5ef8.0503290407.76392bd at posting.google.com>... > Hi, > > I am trying to grok using actor patterns in a gui as explained here by > Andrew Eland: > http://www.andreweland.org/code/gui-actor.html > > The short article explains it using java with which i am not used to > at all. But he does provide a python example using pygtk: > http://www.andreweland.org/code/gui-actor.py > > Could anyone look into it and maybe explain it a bit as i don't really > get at all what's happening? > > In addition I am getting these error when I try to run it: > > GLib-WARNING **: giowin32.c:1654: 3 is neither a file descriptor or a > socket > GLib-CRITICAL **: g_io_add_watch_full: assertion `channel != NULL' > failed > GLib-CRITICAL **: g_io_channel_unref: assertion `channel != NULL' > failed > > Any ideas? > > Thanks... From vze4rx4y at verizon.net Fri Mar 18 21:22:56 2005 From: vze4rx4y at verizon.net (Raymond Hettinger) Date: Sat, 19 Mar 2005 02:22:56 GMT Subject: Pre-PEP: Dictionary accumulator methods References: Message-ID: <42M_d.6892$jt6.6500@trndny07> > > def count(self, value, qty=1): [Aahz] > You mean > def count(self, key, qty=1) > > Right? Yes. Also, there is a typo in the final snippet (pure python version of dictionary of dictionaries). It should read: if key not in d: d[key] = {subkey:value} else: d[key][subkey] = value Raymond From kent37 at tds.net Thu Mar 31 11:44:53 2005 From: kent37 at tds.net (Kent Johnson) Date: Thu, 31 Mar 2005 11:44:53 -0500 Subject: problem running the cgi module In-Reply-To: <1112233555.721396.304990@f14g2000cwb.googlegroups.com> References: <1112233555.721396.304990@f14g2000cwb.googlegroups.com> Message-ID: <424c252e$1_2@newspeer2.tds.net> chris patton wrote: > Hi everyone. I'm trying to code an HTML file on my computer to make it > work with the cgi module. For some reason I can't get it running. This > is my HTML script: > > ------------------------------------------------------ > >

> HOWDY!

> >

> > >
You don't seem to be using a web server at all here - the form action is a file path, not a URL. So the browser is just going to the file system to get the .py file. You can make a simple CGI server by - create a directory caled cgi-bin - put formprinter.py into it - change the form action to action="/cgi-bin/formprinter.py" - Open a dos console to the directory containing the cgi-bin directory - run the command python -c "import CGIHTTPServer; CGIHTTPServer.test()" (Don't do this with Python 2.4, it is broken - use 2.3 or 2.4.1) Kent > > ------------------------------------------------------ > > And here is the python program it's supposed to run with, > formprinter.py: > > ------------------------------------------------------ > > import cgi, cgitb > cgitb.enable() > > form = cgi.FieldStorage() > print '%s
' % form['name'] > > ------------------------------------------------------ > > Whenever I press submit on the HTML document, it returns the code for > "formprinter.py". Can someone tell me what I'm doing wrong? > > -Thanks for any help! > From ali.jan at gmail.com Thu Mar 3 04:20:32 2005 From: ali.jan at gmail.com (Ali) Date: 3 Mar 2005 01:20:32 -0800 Subject: PYGTK, Google Suggest-like GUI In-Reply-To: <1109832063.157281.272140@f14g2000cwb.googlegroups.com> References: <1109832063.157281.272140@f14g2000cwb.googlegroups.com> Message-ID: <1109841632.189702.278190@z14g2000cwz.googlegroups.com> I guess what i am looking for is auto-completion but with a drop-down list... From rkern at ucsd.edu Tue Mar 22 02:46:17 2005 From: rkern at ucsd.edu (Robert Kern) Date: Mon, 21 Mar 2005 23:46:17 -0800 Subject: Begniner Question In-Reply-To: <423fc58b@dnews.tpgi.com.au> References: <423fc58b@dnews.tpgi.com.au> Message-ID: Glen wrote: > #!/usr/local/bin/python > > import sys > > print "1.\tDo Something" > print "2.\tDo Something" > print "3.\tDo Something" > print "4.\tDo Something" > print "5.\tDo Something" > print "6.\tExit" > > choice=raw_input("Please Enter Choice: ") > > if int(choice)==1: > print "Here" > else: > pass > > if int(choice)==2: > else: > pass You need something between the if: and the else: lines. -- Robert Kern rkern at ucsd.edu "In the fields of hell where the grass grows high Are the graves of dreams allowed to die." -- Richard Harter From tzot at sil-tec.gr Sun Mar 20 09:55:20 2005 From: tzot at sil-tec.gr (Christos TZOTZIOY Georgiou) Date: Sun, 20 Mar 2005 16:55:20 +0200 Subject: raise takes a long time References: Message-ID: On Fri, 18 Mar 2005 12:04:02 +0000, rumours say that Robin Becker might have written: >I'm trying to get a handle on a real world problem related to raising an >exception. This is in the reportlab SimpleDoctemplate class. > >The following code takes a very long time (>60 seconds) in Python 2.2, 2.3, 2.4, >but not in 2.1 (at least on windows). > >raise LayoutError("Flowable %s too large on page %d" % (f.identity(30), self.page)) Maybe this is dumb, but how long does the following take? raise LayoutError, "Flowable %s too large on page %d" % (f.identity(30), self.page) >However, the supposedly functionally identical code > >ident = f.identity(30) >raise LayoutError("Flowable %s too large on page %d" % (ident, self.page)) Let's not assume that f.identity(30) runs equally fast in the two cases (for any obscure reasons). Did you time it (ie get the time at the start and end of the function)? >does not take a long time (<< 1 second). The exception LayoutError is trivial >class LayoutError(Exception): > pass -- TZOTZIOY, I speak England very best. "Be strict when sending and tolerant when receiving." (from RFC1958) I really should keep that in mind when talking with people, actually... From apardon at forel.vub.ac.be Fri Mar 18 07:18:38 2005 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Mar 2005 12:18:38 GMT Subject: Python becoming less Lisp-like References: <543c3153frfgbaear473m2jji40hub538k@4ax.com> <87wts9n844.fsf@wilson.rwth-aachen.de> <42361B26.9080605@swiftdsl.com.au> <42362e53$0$31847$636a15ce@news.free.fr> <1gtg08v.ya3l911pd2ldbN%dial#####$$NOSPAM##$#$##@gmail.com> <423755b0$0$28611$636a15ce@news.free.fr> <113f1puo7k9ab7d@corp.supernews.com> Message-ID: Op 2005-03-16, Jeff Shannon schreef : > Bruno Desthuilliers wrote: > >> A few examples: > [...] >> - to get the length of a sequence, you use len(seq) instead of seq.len() >> - to call objects attributes by name, you use [get|set]attr(obj, name >> [,value]) instead of obj.[get|set]attr(name [,value]) > > These are both very consistent applications of a more functional style > of programming, rather than the pure object-oriented style you seem to > desire. It's not that Python is inconsistent; it's that Python is > consistently blending multiple paradigms in a way that uses the best > features of each and (mostly) avoids the worst pitfalls of each. > >> - if x is a class attribute of class A and a is an instance of A, >> a.x=anyvalue create a new instance attribute x instead of modifying A.x > > This is very consistent with the way that binding a name in any scope > will shadow any bindings of that name in "higher" scopes. It is the > same principle by which one is able to use the same name for a > function-local variable that is used for a global variable, without > destroying that global variable. Doing as you suggest would be far > *less* consistent, and would create a special case for class/instance > lookups where there is none now. > Not entirely. The equivallent is imposible in function scope. If function scope would work exactly equivallent as the above the following should work a = 42 def f(): a = a + 1 print a print a And the result should be: 43 42 -- Antoon Pardon From rschroev_nospam_ml at fastmail.fm Wed Mar 2 10:48:03 2005 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 02 Mar 2005 15:48:03 GMT Subject: rearrange text In-Reply-To: <1109777808.966606.9060@o13g2000cwo.googlegroups.com> References: <1109777808.966606.9060@o13g2000cwo.googlegroups.com> Message-ID: Daniel Skinner wrote: > If I have the following text > > var = '1,2,3,4' > > and I want to use the comma as a field delimeter and rearrange the > fields to read > > '1,3,2,4' > > How would I accomplish this in python? I take it you want to swap the second and the third element? That can be accomplished by splitting into a list of fields, swap the second and third element, join the fields back to a string: >>> var = '1,2,3,4' >>> fields = var.split(',') >>> fields ['1', '2', '3', '4'] >>> fields[1], fields[2] = fields[2], fields[1] >>> fields ['1', '3', '2', '4'] >>> newvar = ','.join(fields) >>> newvar '1,3,2,4' -- "Codito ergo sum" Roel Schroeven From bokr at oz.net Fri Mar 25 14:23:37 2005 From: bokr at oz.net (Bengt Richter) Date: Fri, 25 Mar 2005 19:23:37 GMT Subject: Version Number Comparison Function References: <1111764878.482502.69390@g14g2000cwa.googlegroups.com> Message-ID: <4244608d.162536094@news.oz.net> On Fri, 25 Mar 2005 17:02:31 +0100, "Fredrik Lundh" wrote: >"Keith" wrote: > >> Is there a function for comparing version numbers? >> >> E.g. >> >> 0.1.0 < 0.1.2 >> 1.876b < 1.876c >> 3.2.2 < 3.4 > >the following works for many common cases: > >import re > >def cmpver(a, b): > def fixup(i): > try: > return int(i) > except ValueError: > return i > a = map(fixup, re.findall("\d+|\w+", a)) > b = map(fixup, re.findall("\d+|\w+", b)) > return cmp(a, b) # -1 if ab [OT] Visually, I like the nested def fixup, and I realize that for cmpver execution overhead is not likely to be an issue, but in general, what do you think of not being able to write it that way if MAKE_FUNCTION overhead is unacceptable? What if we had something like @sticky('fixup') # evaluate binding only first time def cmpver(a , b): def fixup ... ? Regards, Bengt Richter From cjw at sympatico.ca Tue Mar 8 17:58:48 2005 From: cjw at sympatico.ca (Colin J. Williams) Date: Tue, 08 Mar 2005 17:58:48 -0500 Subject: Announcement: PyMatrix-0.0.1a Released Message-ID: PyMatrix is a package to provide access to the functionality of matrix algebra. This package is currently based on numarray. It includes a statistics module which includes a basic analysis of variance. In the future it is hoped to enhance the generality of the divide operation, to add the transcendental functions as methods of the matrix class and to improve the documentation. The expectation is that Numeric3 will eventually replace numarray and that this will necessitate some changes to PyMatrix Downloads in the form of a Windows Installer (Inno) and a zip file are available at: http://www3.sympatico.ca/cjw/PyMatrix An /Introduction to PyMatrix/ is available: http://www3.sympatico.ca/cjw/PyMatrix/IntroToPyMatrix.pdf Information on the functions and methods of the matrix module is given at: http://www3.sympatico.ca/cjw/PyMatrix/Doc/matrix-summary.html Colin W. From NOT_VALID_please_use_contact_webform at vecerina.com Wed Mar 23 06:34:43 2005 From: NOT_VALID_please_use_contact_webform at vecerina.com (Ivan Vecerina) Date: Wed, 23 Mar 2005 12:34:43 +0100 Subject: Python to c++ conversion problem References: <424141bb$0$12642$3b214f66@tunews.univie.ac.at> Message-ID: "Akdes Serin" wrote in message news:424141bb$0$12642$3b214f66 at tunews.univie.ac.at... >I have a code in python like > if eval('player.moveRoom(SeLinuxMud.Direction.' + x + ')'): # moveRoom > function takes Direction enum as a parameter > > When I am trying to write this code in c++ > if (player->moveRoom(s[1])) //s[1] is a string so it outputs an error > because of not taking enum as a parameter > > How can I change string to enum in c++? Obviously C++ has no eval equivalent, but it also has limited "introspection" at run-time. That is, the executing code has no way to know the compile-time name associated with the enum values. One way to do this mapping manually would be: #include #include enum ERoom { roomEntrance = 0 , roomLobby = 1 , roomCave = 2 }; typedef std::map RoomLookup; typedef RoomLookup::value_type RoomLookupEntry; RoomLookupEntry roomLookupData[3] = { RoomLookupEntry("Entrance", roomEntrance ) , RoomLookupEntry("Lobby", roomLobby ) , RoomLookupEntry("Entrance", roomCave ) }; RoomLookup sRoomLookup(roomLookupData,roomLookupData+3); Then in your code: if (player->moveRoom(sRoomLookup[ s[1] ])) An annoyance with this approach is that your are writing everything twice. There are tricks to avoid that, using the preprocessor, but it has its own drawbacks (see the thread associated with http://groups.google.ca/groups?selm=QJGdnT8LXIMFEGLcRVn-1A%40comcast.com ) But for a game, most typically, the code would load room descriptions from a data file at run-time, and dynamically generate the equivalent of sRoomLookup. I hope this helps, Ivan -- http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form Brainbench MVP for C++ <> http://www.brainbench.com From deets.nospaaam at web.de Thu Mar 31 07:00:21 2005 From: deets.nospaaam at web.de (Diez B. Roggisch) Date: Thu, 31 Mar 2005 14:00:21 +0200 Subject: property and virtuality References: Message-ID: <3b272jF63adiuU1@individual.net> > I cannot override C2._getname instead, because c2.name would print > 'Test2" instead of lala. Clearly, the property stores a reference to the > get and set methods and it is not possible to have it use the new > methods. Creating a new property is the worst - need to duplicate code > and also C3.name is C1.name returns False. :-) It is not a big problem > because I found the solution just I wonder if there is a better way to > "virtualize" property get/set functions. I'm not aware of possibility that works as you first expected. You yourself explained why. But _maybe_ you can use lambda here - that creates the layer of indirection one needs. foo = property(lambda self: self.get_foo(), lamda self,v: self.set_foo(v)) On second thoughts, a metaclass _might_ help here - but it would be rather elaborate: look in the baseclasses for properties that have getters and setters of the same name as some methods in the current class, and replace them, or create a new property with them (I'm not sure if descriptors allow changing their get/set/del methods). I'm not 100% sure if and how good that works (a quick hack would be easy, but to ship around the cliffs of multiple inheritance requires more careful navigation I fear...) -- Regards, Diez B. Roggisch From shitizb at yahoo.com Thu Mar 10 11:51:04 2005 From: shitizb at yahoo.com (Shitiz Bansal) Date: Thu, 10 Mar 2005 08:51:04 -0800 (PST) Subject: How do I set up a timer as a subprocess? In-Reply-To: 6667 Message-ID: <20050310165105.91878.qmail@web53801.mail.yahoo.com> import threading def hello(): print "hello, world" t = threading.Timer(30.0, hello) t.start() # after 30 seconds, "hello, world" will be printed --- Dfenestr8 wrote: > Hi. > > Trying to set up a timer function for my irc bot, > which uses the python > irclib.py. > > If I use time.sleep(20), it tends to freeze up the > bot completely for 20 > secs. That's not what I want though! I want the > program to wait 20 secs, > then perform another function, but in the meantime > be able to accept other > commands. > > How do I do that? > -- > http://mail.python.org/mailman/listinfo/python-list > __________________________________ Do you Yahoo!? Yahoo! Small Business - Try our new resources site! http://smallbusiness.yahoo.com/resources/ From smadim2 at grads.ece.mcmaster.ca Tue Mar 8 20:18:10 2005 From: smadim2 at grads.ece.mcmaster.ca (M.N.A.Smadi) Date: Tue, 08 Mar 2005 20:18:10 -0500 Subject: running a C program with python script Message-ID: <422E4ED2.40505@grads.ece.mcmaster.ca> hi; how can i do the following: 1- run a C program from a python script 2- pass that C program an argument 3- Read the out of the program into a buffer that is local to the script thanks m.smadi From NOmanlio_perilloSPAM at libero.it Sat Mar 5 08:07:33 2005 From: NOmanlio_perilloSPAM at libero.it (Manlio Perillo) Date: Sat, 05 Mar 2005 13:07:33 GMT Subject: Accessing Python parse trees References: <1109877328.005728.317930@z14g2000cwz.googlegroups.com> Message-ID: <935h21laoikg7ao93jj2t4j3ce443iapn3@4ax.com> On 3 Mar 2005 11:15:28 -0800, "Lonnie Princehouse" wrote: >No. I don't think it's possible to read the parse tree used by the >interpreter, especially as it is being created. Here are a couple of >kludgy ideas that might come close, though: Is this a 'limitation' of the current version or it is impossible for the architecture of CPython? What about pypy? > >On a side note, check out the compiler module. You might find it to be >friendlier and more useful than parser. Thanks for the hint. It is what I want. Unfortunately is seem to be not well documented. Anyway, here is an example of what I would like to do: #begin def foo(**kwargs): print kwargs foo(a = 1, b = 2, c = 3) #end In the current implementation kwargs is a dict, but I need to have the keyword argument sorted. Unfortunately subclassing fron dict and installing the class in the __builtin__ module (with the name 'dict') does not work, CPython uses only builtin types. With the compiler module I can obtain the keyword arguments in the order the were specified. The problem is how to do this for every call to foo! Thanks and regards Manlio Perillo From miles__ahead at hotmail.com Fri Mar 11 15:22:01 2005 From: miles__ahead at hotmail.com (miles__ahead at hotmail.com) Date: Fri, 11 Mar 2005 15:22:01 -0500 Subject: Windows Shell Extension Examples esp. IContextMenu Message-ID: Hi. I like to create little utilities for Windows. It's nice to have Shell Integration, such as using the Context Menu. I've googled but haven't seen any Python example code for IContextMenu handlers. Anyone know where I can find some Python examples? Mainly I'm thinking of creating a Python DLL to send messages to running programs when the user selects a command from the Context Menu. TIA From fpm at u.washington.edu Fri Mar 18 10:37:34 2005 From: fpm at u.washington.edu (Frank Miles) Date: Fri, 18 Mar 2005 15:37:34 +0000 (UTC) Subject: fastest postgresql module References: <1Yn_d.2629$SL4.57981@news4.e.nsc.no> Message-ID: In article , Timothy Smith wrote: >Leif B. Kristensen wrote: > >>Timothy Smith skrev: >> >> >> >>>has anyone got some hard numbers on which pg access module is the >>>fastest, i currently use pypgsql, but i can't help but feel it's a >>>little slow. >>>3 seconds to connect, send one query, get th return data. >>>i'm on a adsl 1.5mbit/256kbit link, the server is on a 10/10mbit, and >>>i have a ping of 245ms average. >>>maybe pypgsql does too much backand forth, i don't know. >>> >>> >> >>You might want to try psycopg, it's claimed to be optimized for speed. >> >> >my only issue with psycopg, is last time i looked they had no win32 port? psycopg is available for win32 (though the development version might not be) Try: http://www.stickpeople.com/projects/python/psycopg/ HTH... -frank -- From itsme at yahoo.com Sat Mar 5 14:00:28 2005 From: itsme at yahoo.com (It's me) Date: Sat, 05 Mar 2005 19:00:28 GMT Subject: Newbie getting confused again References: <1110039708.917124.87050@z14g2000cwz.googlegroups.com> Message-ID: Thanks, got it. "M.E.Farmer" wrote in message news:1110039708.917124.87050 at z14g2000cwz.googlegroups.com... > It's me wrote: > > If I have: > > > > a = (1,2,3) > > > > how do I ended up with: > > > > res=[(1), (2), (3), (4), (5)] > > > > without doing: > > > > res=[(a[0]), (a[1]), (a[2]), (4), (5)] > > > > ??? > > > > ps: This is just a nobrainer example of what my real code is trying > to do. > > "a" might have many many elements. That's why the explicit indexing > method > > won't work. > > > > Thanks, > Hello, > List objects have a method called extend(). > It is made for this. > Py> a = [1,2,3] > Py> b = [4,5,6] > Py> a.extend(b) > Py> a > [1, 2, 3, 4, 5, 6] > Since you are a newbie I also suggest you look at > your objects a little and see what they have available. > > Py>dir(a) > ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', > '__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__', > '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', > '__imul__', '__init__', '__le__', '__len__', '__lt__', '__mul__', > '__ne__', '__new__', '__reduce__', '__repr__', '__rmul__', > '__setattr__', '__setitem__', '__setslice__', '__str__', 'append', > 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', > 'sort'] > > Then you can try and get some help from Python. > Py>help(a.extend) > Help on built-in function extend: > > extend(...) > L.extend(iterable) -- extend list by appending elements from the > iterable > > And finally use pydoc it is very helpful. > Cl> python pydoc -g > hth, > M.E.Farmer > From antonyliu2002 at yahoo.com Thu Mar 3 22:15:05 2005 From: antonyliu2002 at yahoo.com (Anthony Liu) Date: Thu, 3 Mar 2005 19:15:05 -0800 (PST) Subject: convert a list to a string? In-Reply-To: Message-ID: <20050304031505.47060.qmail@web54503.mail.yahoo.com> Oh, yes, that's a cool function! I did that before but have forgotten. Thanks a lot! --- Tony Meyer wrote: > > Suppose I have a list > > > > myList = ["this", "is", "a", "sample", "list"] > > > > If I don't want to iterate through it and > concatenate > > the list elements, how do I easily convert it to a > > string like > > > > "this is a sample list" > > " ".join(myList) > > =Tony.Meyer > > __________________________________ Celebrate Yahoo!'s 10th Birthday! Yahoo! Netrospective: 100 Moments of the Web http://birthday.yahoo.com/netrospective/ From m_webber_sydney at yahoo.com.au Thu Mar 17 08:31:04 2005 From: m_webber_sydney at yahoo.com.au (Matthew) Date: 17 Mar 2005 05:31:04 -0800 Subject: Is Python like VB? References: <39sj7hF62s0etU1@individual.net> Message-ID: "Mike Cox" wrote in message news:<39sj7hF62s0etU1 at individual.net>... > As you may or may not know, Microsoft is discontinuing Visual Basic in favor > of VB.NET and that means I need to find a new easy programming language. I > heard that Python is an interpreted language similar to VB. This means that > it doesn't have all the hard stuff like pointers, classes and templates like > C, C++ and assembly language. > > Where I work we use Microsoft Office with a lot of customization using > Visual Basic. I would like to switch to Python to do it since VB is being > discontinued. Would Python meet our requirements? I need to make lots of > GUI applications (message boxes, forms, etc.) and do the underlying business > logic too. > > Thanks in advance. The macro language used within Microsoft Office products is called VBA - Visual Basic for Applications. It's similar to but not the same as VB - Visual Basic. You message hinted that it might be VBA, and not VB, that you use. If it really is VBA, then that MAY be unaffected by the drop of support for VB. From ksenia.marasanova at gmail.com Wed Mar 16 05:56:07 2005 From: ksenia.marasanova at gmail.com (Ksenia Marasanova) Date: Wed, 16 Mar 2005 12:56:07 +0200 Subject: getting data with proper encoding to the finish In-Reply-To: <1110852102.363415.160010@f14g2000cwb.googlegroups.com> References: <1110835456.244059.307710@z14g2000cwz.googlegroups.com> <1110847827.810511.51610@z14g2000cwz.googlegroups.com> <1110852102.363415.160010@f14g2000cwb.googlegroups.com> Message-ID: <130df19305031602564f366bce@mail.gmail.com> John, Serge, thanks for your help! utf-16le encoding didn't help. I had however to solve it yesterday, so I used csv module to create CSV file and then import it in Excel. Excel still had troubles with accented characters, but this is another story: it seems that Office 2004 Excel (for Mac, but I assume the PC version is no better) cannot import UTF-8 encoded text files. Encoding CSV file with Latin1 encoding finally did work. Now back to the Excel story, I also think that there is something wrong with pyExcelWriter or the way I use it. CSV file generation was okay, so I think there is nothing wrong with my data, or XML parser. I will resume in a few days with pyExcelWriter and will post the results here, but anyway, many thanks for your time and explanation! -- Ksenia From s.varun at gmail.com Wed Mar 2 13:23:04 2005 From: s.varun at gmail.com (Varun) Date: 2 Mar 2005 10:23:04 -0800 Subject: Python Online Programming Contest In-Reply-To: References: <1109278779.955986.193860@z14g2000cwz.googlegroups.com> <1109283053.971905.27670@z14g2000cwz.googlegroups.com> <1109295016.597170.21350@o13g2000cwo.googlegroups.com> Message-ID: <1109787784.079234.58700@o13g2000cwo.googlegroups.com> Hi, The results of OPC (online programming contest) is out. The statistics of python usage is available at http://www.samhita.info/opc/status.php. Regards, -OPC Team From stephen.thorne at gmail.com Wed Mar 2 03:03:59 2005 From: stephen.thorne at gmail.com (Stephen Thorne) Date: Wed, 2 Mar 2005 18:03:59 +1000 Subject: Question - What is a faster alternative to recursion? In-Reply-To: <42256432.8010809@elemental-systems.com> References: <4225288F.5060002@elemental-systems.com> <42254905.1080408@elemental-systems.com> <200503020638.02147.modelnine@ceosg.de> <42256432.8010809@elemental-systems.com> Message-ID: <3e8ca5c80503020003464ba515@mail.gmail.com> On Wed, 02 Mar 2005 00:58:58 -0600, actuary77 wrote: > Yes, iteration is 10000000000 times faster than recursion. > > The problem I have is: > > # need to call this function 50 times with seed of 10 > (afunc(afunc(afunc(... afunc(10)) > > required_iterations_ 50 > function: afunc(x): x**.5 + 1000 * x + 46. > initial_seed: 10 > > Result => afunc(afunc(afunc(afunc(afunc(afunc ... (_aseed) > > What is the fastest way to do this without using recursion? > > With recursion: > ================ > > def rec(afunc,n,x): > y = afunc(x) > if n == 0: > return y > else: > return rec(afunc,n-1,y) > > def myfunc(x): > return x**.5 + 1000 * x + 46. > > from time import time > > _b=time() > _y = rec(myfunc,50,10) > _e=time() > _t=_e-_b > print "result: %r time: %f\n" % (_y,_t) > > output: > result: 1.00493118428005e+154 time: 0.030000 > > Is there a much faster way? Sure. [sthorne at wendy tmp]$ python timeit.py -s 'from recursive import calculate' 'calculate(100, 10)' 1000 loops, best of 3: 295 usec per loop [sthorne at wendy tmp]$ python timeit.py -s 'from iterative import calculate' 'calculate(100, 10)' 10000 loops, best of 3: 134 usec per loop [sthorne at wendy tmp]$ cat iterative.py def calculate(repeats, value): for x in range(repeats): value = value ** .5 + 1000*x + 46 return value [sthorne at wendy tmp]$ cat recursive.py def rec(afunc,n,x): y = afunc(x) if n == 0: return y else: return rec(afunc,n-1,y) def myfunc(x): return x**.5 + 1000 * x + 46. def calculate(repeats, value): rec(myfunc, repeats, value) As you can see, the iterative solution actually results in less code too ;) Stephen. From deetsNOSPAM at web.de Sun Mar 20 16:35:29 2005 From: deetsNOSPAM at web.de (Diez B. Roggisch) Date: Sun, 20 Mar 2005 22:35:29 +0100 Subject: simultaneous copy to multiple media References: <3a52b3F66fideU1@individual.net> <3a5ihoF66l2n4U1@individual.net> <3a67j3F67omldU1@individual.net> Message-ID: > 2) if I understand it right, an USB controller is connected to > to the PCI bus and there can be many separate USB > controller on one PC True. > 3) the theoreticall speed of USB (430 MByte/s?) is much > higher as the experienced 15 MByte/s, probably due to slow > controller on the side of the external storage media, so > maybe even on one USB line I will have the chance to > use it full capacity connecting many slow devices > (I can't imagine, that USB goes down with the speed to > the speed of the slowest component connected, does it?) Nope. Or yes. Here comes into play why Heiko said think of what USB stands for. While the devices appear to be responsive concurrently (the bus arbitration and multiplexing/demultiplexing is tranparent to the user), it still is a serial bus, so at a given point in time you can only write to _one_ device. And if that device is limited in its speed, you're doomed. The only thing I could imagine is that if you send small bursts that don't make the write cache full, it _might_ be possible to switch fast between the devices and thus write the data faster, as the devices can try and write the data to disk while the others are feeded. But I'm on no sure ground here with that assumption, and it certainly would depend on how the usb-ata-controller deals with that. You said yourself that you only had 15MB/sec, so it doesn't look to good. To make this work would certainly be a deep lowlever driver hack and nowhere in the scope of python per se. > 4) with 45 MByte/s I could theoretically simultaneously > supply three separate data streams to three USB > controller writing with 15 MByte/s each out to the > external storage media. That might be the case if you use three real separate controllers. But that will depend on how the OS deals with these, if you really achieve the theoretical throughoutput. > 5) watching the low CPU usage while writing to USB > shows me, that CPU-time is not a problem. That is certainly true - the bottleneck are the buses. -- Regards, Diez B. Roggisch From werner_DOT_merkl_ at _fujitsu_DASH_siemens.com Thu Mar 3 03:34:46 2005 From: werner_DOT_merkl_ at _fujitsu_DASH_siemens.com (Werner Merkl) Date: Thu, 03 Mar 2005 09:34:46 +0100 Subject: PythonWin, AutoDoc and german keyboards... Message-ID: Hallo, PythonWin is really great and like to use it all the time. But, I use to an us keyboard and get support strings (.__doc__). On the other side, most of my colleges use German keyboards and the do not get these strings at all. We are using: - Python 2.4 - PyWin32 203 Here is an example: ------------------- When we enter range with us keyboard we get: >>> range( [range([start,] stop[, step]) -> list of integers] When we do this with German keyboard we get... nothing, except we enter: >>> range) [range([start,] stop[, step]) -> list of integers] You see, if we press ")" on German KB, which is "(" on us KB we get the help... BTW: Changes to Python24\Lib\site-packages\pythonwin\pywin\default.cfg didn't help. Is this a known issue? And is there a work around? Or do we have to take an other IDE like SPE? Thank you in advance Werner Merkl From dirgesh at gmail.com Mon Mar 28 23:12:18 2005 From: dirgesh at gmail.com (GujuBoy) Date: 28 Mar 2005 20:12:18 -0800 Subject: Win32 or Unix check in python Message-ID: <1112069538.920445.223840@g14g2000cwa.googlegroups.com> how can you check in python at the beginning if you running the app in WIN32 or UNIX. please help From nick at craig-wood.com Tue Mar 1 01:48:03 2005 From: nick at craig-wood.com (Nick Craig-Wood) Date: 01 Mar 2005 06:48:03 GMT Subject: Explicit or general importing of namespaces? References: <1109588238.491145.52060@l41g2000cwc.googlegroups.com> <38gc2tF5o34sbU1@individual.net> <7x7jksplbp.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Peter Hansen writes: > > Ultimately more important than mere "pollution" are the > > latent problems this can cause if any of the names in > > the original module can ever be re-bound. > > You know, this is another reason the compiler really ought to (at > least optionally) check for such shadowing and have a setting to > enforce user declarations, like perl's "use strict". As a (mostly) ex-perl user I wouldn't like to see python go there - it seems like a rather slippery slope (like the warnings subsystem). This is surely a job for pychecker / pylint? -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bdesth.quelquechose at free.quelquepart.fr Sat Mar 19 15:17:05 2005 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 19 Mar 2005 21:17:05 +0100 Subject: Variable Variable In-Reply-To: <1111223443.923496@newsmaster-03.atnet.at> References: <1111223443.923496@newsmaster-03.atnet.at> Message-ID: <423c8568$0$14313$636a15ce@news.free.fr> Tanteauguri a ?crit : > Hi List, is there in python a variable variable like in PHP ($$var)? Hopefully, no. See other answers in that thread for pythonic idioms. From sc0rp at hot.pl Mon Mar 21 11:53:34 2005 From: sc0rp at hot.pl (Jacek Trzmiel) Date: Mon, 21 Mar 2005 17:53:34 +0100 Subject: simultaneous copy to multiple media References: <3a52b3F66fideU1@individual.net> <3a5ihoF66l2n4U1@individual.net> <3a7g2pF685bo2U1@individual.net> Message-ID: <423EFC0E.8F46F9A1@hot.pl> > > This is small tool I've wrote, that does use large memory buffers with > > asynchronous I/O to copy file. Claudio Grondi wrote: > Thank you! > This (with a drawback of blocking the entire system) does it! > ( dzie? dobry i dzi?kuj? za t? konstruktywn? odpowied? > na moje pytanie ) :) > From my point of view this thread has reached > its end (I have a solution I can live with), except if > someone would like to contribute or point to a > better multicopy.exe which does not block the system Symptoms (high cpu usage, unresponsive system) look similar to situation when you try to read/write as fast as possible from/to IDE drive running in PIO mode. I think that it's either USB driver problem, or inherent design flaw in USB (anyone?). Anyway, I've added buffersize and sleeptime options to multicopy, so you may try to throttle it down. Download it here: http://mastermind.com.pl/multicopy/ HTH, sc0rp. From claudio.grondi at freenet.de Sun Mar 20 11:16:49 2005 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 20 Mar 2005 16:16:49 -0000 Subject: simultaneous copy to multiple media References: <3a52b3F66fideU1@individual.net> Message-ID: <3a5ihoF66l2n4U1@individual.net> I am on a Widows 2000 box using the NTFS file system. Both up to now suggested approaches as - tee.exe (where I used the http://david.tribble.com/dos/tee.exe DOS-port with redirecting stdout to NULL) and - parallel copy (hoping caching does the job) are by far slower than the consecutive copy: single copy speed 12-15 MByte/s which gives effectively 6-7 MByte/s, tee.exe or twice copy in parallel 1-3 MByte/s. Any other suggestions except writing an own optimised version of tee.exe, because it is so easy to come up with: while(c=getchar()){fputc(c,fp1);fputc(c,fp2);} ? Is there maybe a way to use a direct DMA transfer to multiple target destinations (I copy to drives connected via USB ports) ? Can someone point me in the right direction? Claudio "Claudio Grondi" schrieb im Newsbeitrag news:3a52b3F66fideU1 at individual.net... > I would like to save time copying the same file > (>6 GByte) to various different target storage > media connected to the system via USB. > > Is there a (Python or other) tool able to help me > to do this, so that I don't need to copy the > source file first to the first media, then to the > second, etc.? > > Claudio > > From ap22 at leicester.ac.uk Mon Mar 21 08:53:10 2005 From: ap22 at leicester.ac.uk (Prescott, A.) Date: Mon, 21 Mar 2005 13:53:10 -0000 Subject: Problem installing Python in Win98se Message-ID: <6728E9270FDF8D44A41AF135DBB553E82C68D1@sumac.cfs.le.ac.uk> Hi, I want to install Python on my Windows 98se system, but although I followed the instructions carefully, it won't run. Here's a copy of the Web instructions I followed, from Python.org: "Starting with the Python 2.4 releases the Windows Python installer is being distributed as a Microsoft Installer (.msi) file. To use this, the Windows system must support Microsoft Installer 2.0. Just save the installer file python-2.4.msi to your local machine, then double-click python-2.4.msi to find out if your machine supports MSI. If it doesn't, you'll need to install Microsoft Installer first. Many other packages (such as Word and Office) also include MSI, so you may already have it on your system. If not, you can download it freely from Microsoft for Windows 95, 98 and Me" The installer I downloaded from Microsoft and ran is called InstMsiA.exe. That seemed to install fine, but the .msi file still won't run. Any ideas what I'm doing wrong? Thanks in advance, Andy -------------- next part -------------- A non-text attachment was scrubbed... Name: winmail.dat Type: application/ms-tnef Size: 3793 bytes Desc: not available URL: From steve at holdenweb.com Tue Mar 8 13:18:04 2005 From: steve at holdenweb.com (Steve Holden) Date: Tue, 08 Mar 2005 13:18:04 -0500 Subject: looking for way to include many times some .py code from anotherpython code In-Reply-To: <422DCE43.10108@ribosome.natur.cuni.cz> References: <422d9b47$1@nntp0.pdx.net> <395ncpF5sl0i3U1@individual.net> <422DCE43.10108@ribosome.natur.cuni.cz> Message-ID: Martin MOKREJ? wrote: > Peter Hansen wrote: > >> Martin MOKREJ? wrote: >> >>> Am I so deperately fighting the language? No-one here on the list >>> needs to set hundreds variables at once somewhere in their code? >> >> >> >> Nobody needs to do that. As others have pointed out, creating variables >> implies wanting to access them distinctly, not as a whole group. If >> you are just going to access them as a group, use contain objects such >> as lists or dicts or a custom class, not individual variables. > > > I understand, but this is unfortunately not my case now. It's really > about assigning data from mysql to some variables and getting them later > checked. The checks will be different for most variables and will even > differ if I read from sql or alternatively I instantiate first new data > obtained from web interface and write subsequently into sql (for example, > all row ID's won't be known while instantiating the objects). > >>> Now have to figure out how to assign them easily into the XML tree. >> >> >> >> This might be the hint that others were hoping for, about your >> real requirements. Do you mean to say that the whole reason >> you have for assigning hundreds of variables is to go and >> shove the values right back into another data structure such >> as an XML document? If so, trust us, you very likely don't > > > No, the xml is another reason why I wanted to walk over the __dict__ > of some object and let something magically constrcut the XML tree for me. > But this is really another, distinct problem from teh one I posted > originally. > >> want to do it by assigning and then referencing hundreds of >> variables. > > > I need to test almost every for it's content. Some tests > are just that the value is non-empty (few cases), but in most cases > a lot more checks (only certain values allowed, or only int type allowed, > or only \w is allowed ...). > > FYI: The program/database runs at the moment under php + mysql. > I will be *very* surprised if you can't get a much better (i.e. easier and more efficient) solution by stepping back from the programming details for a moment and explaining what it is you are actually trying to achieve in user-space. Can you describe the problem you are trying to solve, rather than the solution you are hoping to adopt? regards Steve From steven.bethard at gmail.com Tue Mar 15 18:51:29 2005 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 15 Mar 2005 16:51:29 -0700 Subject: Python becoming less Lisp-like In-Reply-To: <423756a5$0$28611$636a15ce@news.free.fr> References: <543c3153frfgbaear473m2jji40hub538k@4ax.com> <87zmx5n87e.fsf@wilson.rwth-aachen.de> <87vf7tiblj.fsf@wilson.rwth-aachen.de> X-Antivirus: avast! (VPS 0510-1, 03/11/2005), Outbound message <423756a5$0$28611$636a15ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: >> class CommandMenuSelectionCallback: >> def __init__(self, key): >> self.key = key >> >> def __call__(self): >> print self.key > > > Looks like Java. When was the last time you used Java? It has no support for using classes as callable objects. __call__ would have to be invoked manually; you definitely couldn't have a CommandMenuSelectionCallback instance masquerading as a function as this code (basically) does. STeVe From guy at NOSPAM.r-e-d.co.nz Thu Mar 3 18:13:04 2005 From: guy at NOSPAM.r-e-d.co.nz (Guy Robinson) Date: Fri, 04 Mar 2005 12:13:04 +1300 Subject: creating .NET clients with python In-Reply-To: <1109890600.046282.299540@f14g2000cwb.googlegroups.com> References: <1109890600.046282.299540@f14g2000cwb.googlegroups.com> Message-ID: Thanks Alan, Are you saying I can create python .net clients with PythonNet. My understanding is I can only use .net clients from python not the other way around. Do you have an example showing creating a .net client in python? regards, Guy yaipa wrote: > Guy, > > I can tell you that pythonNet is quite far along, rel 1, Beta 4 > actually. > > here is a c.l.p link to the three major releases. > > http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/ddfc68767901007c/445f2052948d93e2?q=pythonnet&_done=%2Fgroup%2Fcomp.lang.python%2Fsearch%3Fgroup%3Dcomp.lang.python%26q%3Dpythonnet%26qt_g%3D1%26searchnow%3DSearch+this+group%26&_doneTitle=Back+to+Search&&d#445f2052948d93e2 > > Cheers, > > --Alan > > > Guy Robinson wrote: > >>Hello, >> >>Can anyone confirm if there is a python library that can allow me to > > create .NET > >>clients in python. >> >>My understanding is both IronPython and python for .NET can't create > > python .net > >>clients? >> >>Regards, >> >>Guy > > From ' at '.join([..join(['fred', 'dixon']), ..join(['gmail', Sun Mar 27 15:42:29 2005 From: ' at '.join([..join(['fred', 'dixon']), ..join(['gmail', (' at '.join([..join(['fred', 'dixon']), ..join(['gmail',) Date: 27 Mar 2005 12:42:29 -0800 Subject: Cross platform distribution of standalone executable In-Reply-To: References: <1111946358.233599.253370@z14g2000cwz.googlegroups.com> Message-ID: <1111956149.938293.76450@g14g2000cwa.googlegroups.com> don't count out py2exe, especially if your using pywin32's From mrovner at propel.com Tue Mar 29 13:29:37 2005 From: mrovner at propel.com (Mike Rovner) Date: Tue, 29 Mar 2005 10:29:37 -0800 Subject: truncating a file from the top down In-Reply-To: References: Message-ID: Right. Thanks for the correction. Fredrik Lundh wrote: > Mike Rovner wrote: > > >>if os.stat says the_file is too big: >> fh = open(the_file, 'rb') >> fh.seek(2008, 2) > > > should be > > fh.seek(-2008, 2) > > right? > > >> data = fh.read() >> fh.close() >> assert len(data)==2008 # you may want some error processing here >> fh = open(the_file, 'wb') >> fh.write(data) >> fh.close() > > > or > > if os.path.getsize(the_file) > TOO_BIG: > fh = open(the_file, 'rb+') > fh.seek(-2008, 2) > data = fh.read() > fh.seek(0) # rewind > fh.write(data) > fh.truncate() > fh.close() > > > > > From actuary77 at elemental-systems.com Tue Mar 1 21:44:31 2005 From: actuary77 at elemental-systems.com (actuary77) Date: Tue, 01 Mar 2005 20:44:31 -0600 Subject: Help- Simple recursive function to build a list Message-ID: <4225288F.5060002@elemental-systems.com> I am trying to write simple recursive function to build a list: def rec(n,alist=[]): _nl=alist[:] print n,_nl if n == 0: print n,_nl return _nl else: _nl=_nl+[n] rec(n-1,_nl) _nl=[] _nl=rec(4) print _nl ### shouldn't this work? _nl=rec(4) The output is: 4 [] 3 [4] 2 [4, 3] 1 [4, 3, 2] 0 [4, 3, 2, 1] 0 [4, 3, 2, 1] None None Question: ============ Why isn't the function returning a list? Why is function returning None? Any guidance from one of you pro's would be greatly appreciated. Thanks, DKoch actuary77 at elemental-systems.com From dalke at dalkescientific.com Sat Mar 5 10:52:42 2005 From: dalke at dalkescientific.com (Andrew Dalke) Date: Sat, 05 Mar 2005 15:52:42 GMT Subject: Appeal for python developers References: <87hdjq40af.fsf@wilson.rwth-aachen.de> Message-ID: Torsten Bronger wrote: > Accordings to Stroustrup's C++ book, the only good reason for goto > statements in a language is to have it in computer-generated code. I've needed goto statements when translating old code written with gotos. > Most gotos are disguised function calls, so > just copy the code in a "def". And loops can be translated to > "while"s almost trivially. True, but there are some that aren't easily translated. I remember implementing code from Knuth. I think it was a prime generation algorithm. It was MIX code that interwove two loops and couldn't be easily untangled. Since I just wanted to text it out I used C++ which had both gotos and priority queues built in. Andrew dalke at dalkescientific.com From g.horvath at mx.at Tue Mar 15 11:16:34 2005 From: g.horvath at mx.at (Gregor Horvath) Date: Tue, 15 Mar 2005 16:16:34 GMT Subject: Why tuple with one item is no tuple Message-ID: Hi, >>>type(['1']) >>>type(('1')) I wonder why ('1') is no tuple???? Because I have to treat this "special" case differently in my code. -- Greg From http Fri Mar 25 03:50:24 2005 From: http (Paul Rubin) Date: 25 Mar 2005 00:50:24 -0800 Subject: Queue.Queue-like class without the busy-wait References: <1111707620.556818.289300@g14g2000cwa.googlegroups.com> Message-ID: <7xmzsshzxr.fsf@ruckus.brouhaha.com> Antoon Pardon writes: > I started once, using the Timer class in the Threading Module to > break the lock. However the Timer class uses the same kind of > sleep-polling loop, to delay the exection and allow an intermediate > cancel, as the loop that is used in Queue.Queue, so that was no > gain. I've never checked this code but it wouldn't have occurred to me that Queue uses any kind of timeout loop. Can't it work the obvious way with a semaphore? From philipasmith at blueyonder.co.uk Thu Mar 31 01:55:39 2005 From: philipasmith at blueyonder.co.uk (Philp Smith) Date: Thu, 31 Mar 2005 06:55:39 GMT Subject: Pari Python Message-ID: Hi I'm interested to try Pari Python but haven't had much success in the past compiling such packages for Windows. Has anyone any advice or is there somewhere out there a precompiled version? Thanks Phil From finite.automaton at gmail.com Wed Mar 23 19:45:56 2005 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 23 Mar 2005 16:45:56 -0800 Subject: newbie help References: <1111615030.326032.62650@o13g2000cwo.googlegroups.com> <1111617044.361876.245460@o13g2000cwo.googlegroups.com> <1111620665.791291.55190@o13g2000cwo.googlegroups.com> <1111622758.662218.4880@o13g2000cwo.googlegroups.com> Message-ID: <1111625156.347645.147860@z14g2000cwz.googlegroups.com> buf1 = [None] * 512 buf2 = [None] * 512 (Not quite the same as C because the list isn't filled with gibberish...) From ray_usenet at yahoo.com Thu Mar 24 03:22:09 2005 From: ray_usenet at yahoo.com (Ray) Date: 24 Mar 2005 00:22:09 -0800 Subject: Suggestions for a Java programmer Message-ID: <1111652529.942487.9190@l41g2000cwc.googlegroups.com> Hello there, I've been programming in Java for about 8 years now, but lately I've been hearing a lot about Python and I'm really interested in learning more about it. I've read the tutorial, and some books (core python programming is one), but there's one thing that's still missing: how to use Python the "Python" way. I found learning C# was a breeze for me because the language shares a lot of concepts and notions with Java--I can always say: "I do X this way in Java, I should be able to do X this way too in C#", and usually I'm not far off the mark. But Python is different enough that, even though some basic concepts do translate easily, idioms and effective usage of it don't come easy. I can't help thinking that when I'm writing Python, I'm actually writing Java in Python. Not Python in Python. Can you point me to "Python for Java Programmers" resources? I found one blog, but that only touched the tip of the iceberg, I feel. I know that as I use Python more and read more books and read how experienced Python programmers code, eventually I'll find it out. But I'd like to expedite that process if possible. What are your suggestions? Thank you! Ray From siona at chiark.greenend.org.uk Fri Mar 11 08:05:00 2005 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 11 Mar 2005 13:05:00 +0000 (GMT) Subject: injecting "set" into 2.3's builtins? References: <16943.42928.611124.3810@montanaro.dyndns.org> Message-ID: <8DA*FxgJq@news.chiark.greenend.org.uk> Stephen Thorne wrote: >I have: >try: > set >except NameError: > from sets import Set as set > >in my code in a few places. Is there any reason to prefer this over the idiom I have: if sys.version_info < (2, 4): from sets import Set as set ? (I've also used the same kind of trick to provide enumerate when a script is being run with pre-2.3.) -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ ___ | "Frankly I have no feelings towards penguins one way or the other" \X/ | -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From hongqn at gmail.com Thu Mar 24 05:45:43 2005 From: hongqn at gmail.com (Qiangning Hong) Date: 24 Mar 2005 02:45:43 -0800 Subject: unittest help Message-ID: <1111661143.935468.58500@l41g2000cwc.googlegroups.com> I want to apply TDD (test driven development) on my project. I am working on a class like this (in plan): # file: myclass.py import _extmod class MyClass(object): def __init__(self): self.handle = _extmod.open() def __del__(self): _extmod.close(self.handle) def some_stuff(self): _extmod.foobar(self.handle) ... As you see, it is an OO wrapper on _extmod, which is a pyrex extension module. The question is: how to unittest this class? As the _extmod is hardware-dependent, I want to use a mock class to replace it in unit test. But how can I let myclass in unittest to import the mock class? Like the following: class MyClassTest(unittest.TestCase): def setUp(self): import myclass import mocklib myclass.change_extmod(mocklib.MockExtMod()) self.testobj = myclass.MyClass() # here MyClass.__init__ will call the open # method of MockExtMod class instead of # _extmod.open() ... How to implement the change_extmod? (Or maybe my idea is totally wrong?) From pd_mct at yahoo.com.au Sun Mar 13 00:48:08 2005 From: pd_mct at yahoo.com.au (Pete) Date: Sun, 13 Mar 2005 05:48:08 GMT Subject: try / except not worknig correctly In-Reply-To: <1110675977.831462.17830@l41g2000cwc.googlegroups.com> References: <1110673238.589776.40870@l41g2000cwc.googlegroups.com> <1110675977.831462.17830@l41g2000cwc.googlegroups.com> Message-ID: <4233d417$1@news.comindico.com.au> '@'.join([..join(['fred','dixon']),..join(['gmail','com'])]) wrote: > 1) the tutor list is really slow. but thanks. > > 2) Thanks Brain, i was missing the string bit. the code i posted (opps) > was not exactly where i was having problems, it just looked like it. > > also thanks for the 'in' test, that will come in handy. > i am using chain because i need to do something different for each > twest. > > is there a better way to return a tuple for each choice ? > You could try this: >>> def doA(): print 'doing A' >>> def doB(): print 'doing B' >>> processFuncs = dict() >>> processFuncs['A'] = doA >>> processFuncs['B'] = doB >>> while 1: print 'Enter option:' try: myInput = raw_input('A or B?') myInput = myInput.upper() func = processFuncs[myInput] func() except KeyError, e: print 'Opps wrong option', e pass Enter option: A or B?A doing A Enter option: A or B?B doing B Enter option: A or B?C Opps wrong option 'C' Enter option: A or B? From peter at engcorp.com Wed Mar 30 15:26:16 2005 From: peter at engcorp.com (Peter Hansen) Date: Wed, 30 Mar 2005 15:26:16 -0500 Subject: Using something other than ';' to separate statements In-Reply-To: References: <-4KdnSgFwtqMRtffRVn-oA@powergate.ca> Message-ID: <69qdneIagbIDltbfRVn-pg@powergate.ca> Michael Hoffman wrote: > Jaime Wyant wrote: > >> # This won't work >> if a > 5: print "a > 5";else print "Doh" > > > This will: > > ["Doh", "a > 5"][a > 5] > > I highly discourage using it though--it's somewhat obtuse. It's also limited to evaluating expressions, which is probably not very useful to the OP... From sjmachin at lexicon.net Wed Mar 16 18:43:06 2005 From: sjmachin at lexicon.net (John Machin) Date: 16 Mar 2005 15:43:06 -0800 Subject: computing a weighted sum In-Reply-To: References: <1110984549.526360.175920@f14g2000cwb.googlegroups.com> Message-ID: <1111016586.298564.160270@f14g2000cwb.googlegroups.com> Fernando Perez wrote: > andreif at mail.dntis.ro wrote: > > > Suppose I have a list of n floats x and a list of n floats w and I want > > to compute x[0]*w[0] + .. + x[n-1]*w[n-1]. > > > > Is there some elegant expression (perhaps using lambda) to have it done > > in one statement ? As in : > > y = lambda x,w : ... > > > > I ask because the way I am doing it now : > > y = 0 > > for i in range(0,n): y += x[i]*w[i] > > > > doesn't seem very pythonic :) > > > > Thanks, > > Andrei > > > > import Numeric > print Numeric.dot(x,w) Indeed. Horses for courses. Anyway, people who reinvent the wheel often fall to arguing among themselves whose polygon is the best approximation to a circle, and forget to reinvent the axle. Wouldn't happen in this newsgroup, of course :-) From mikecoxlinux at yahoo.com Thu Mar 17 00:33:36 2005 From: mikecoxlinux at yahoo.com (Mike Cox) Date: Wed, 16 Mar 2005 21:33:36 -0800 Subject: Is Python like VB? Message-ID: <39sj7hF62s0etU1@individual.net> As you may or may not know, Microsoft is discontinuing Visual Basic in favor of VB.NET and that means I need to find a new easy programming language. I heard that Python is an interpreted language similar to VB. This means that it doesn't have all the hard stuff like pointers, classes and templates like C, C++ and assembly language. Where I work we use Microsoft Office with a lot of customization using Visual Basic. I would like to switch to Python to do it since VB is being discontinued. Would Python meet our requirements? I need to make lots of GUI applications (message boxes, forms, etc.) and do the underlying business logic too. Thanks in advance. From postmaster at castleamber.com Thu Mar 24 18:22:44 2005 From: postmaster at castleamber.com (John Bokma) Date: 24 Mar 2005 23:22:44 GMT Subject: Python docs [was: function with a state] References: <1110096425.669042.11050@o13g2000cwo.googlegroups.com> <1110126829.223750.10070@f14g2000cwb.googlegroups.com> <1110330451.100511.179530@o13g2000cwo.googlegroups.com> <1111705341.697924.64370@l41g2000cwc.googlegroups.com> Message-ID: Xah Lee wrote: > The Python doc is relatively lousy, from content organization to the > tech writing quality. So write your own or fork the current one. I doubt if that's a problem. Did you read Dive into Python? -- John Small Perl scripts: http://johnbokma.com/perl/ Perl programmer available: http://castleamber.com/ Happy Customers: http://castleamber.com/testimonials.html From Scott.Daniels at Acm.Org Mon Mar 21 12:12:39 2005 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 21 Mar 2005 09:12:39 -0800 Subject: Python limericks (was Re: Text-to-speech) In-Reply-To: References: <61986976a626d1ea12d840b72f4b1a2a@conncoll.edu> <423DE896.4020807@holdenweb.com> Message-ID: <423efbac$1@nntp0.pdx.net> Tim Churches wrote: > ... > My first attempt (which does not scan properly): > > A Dutch mathematician most prophetic, > Did invent a language, name herpetic. > With design quite intelligent, > And syntax mostly elegant, > Big ideas could be made non-hypothetic. To improve the scan: A mathematician, prophetic, invented a language, herpetic. decidedly brilliant, syntacticly elegant, Made ideas far less hypothetic. --Scott David Daniels Scott.Daniels at Acm.Org From dbasch at yahoo.com Wed Mar 16 11:56:54 2005 From: dbasch at yahoo.com (Derek Basch) Date: 16 Mar 2005 08:56:54 -0800 Subject: Minidom empty script element bug References: <42376C3B.1070209@v.loewis.de> <1110941103.774422.155720@g14g2000cwa.googlegroups.com> <4237de56$0$28922$9b622d9e@news.freenet.de> Message-ID: <1110992214.631301.19030@f14g2000cwb.googlegroups.com> Cross post from XML-SIG: --- Walter D?rwald wrote: > Martin v. L?wis sagte: > > Derek Basch wrote: > > >[...] > >> How do I get minidom to NOT render an empty script element? Should I > submit a bug report? > > > > That said, I think there is a simple solution: add an empty Text node to > the script element: > > > > script_node_0.appendChild(doc.createText(u"")) > > > > [Disclaimer: this is untested; from reading the source, I think it should > work] > > If this doesn't work, you might want to try XIST > (http://www.livinglogic.de/Python/xist) > instead of minidom. XIST knows that the script element is not EMPTY, and when > the > output is in HTML compatible XML an end tag will be produced: > > >> from ll.xist.ns import html > >>> print html.script(type="text/javascript", > src="../test.js").asBytes(xhtml=1) > > > Using pure XML mode gives: > > >>> print html.script(type="text/javascript", > src="../test.js").asBytes(xhtml=2) >